Skip to main content

[Repost] Three Usage Scenarios of @ConfigurationProperties Annotation in SpringBoot

Article source: Three Usage Scenarios of @ConfigurationProperties Annotation in Spring Boot

In Spring Boot, the @ConfigurationProperties annotation has three usage scenarios, though typically we only use one of them most often. This article introduces all three scenarios.

Scenario 1

Use @ConfigurationProperties and @Component annotations on the bean definition class, where @Component represents similar bean instantiation annotations.

Basic usage example:

// Annotations that define a class as a bean, such as @Component, @Service, @Controller, @Repository
// or @Configuration
@Component
// Indicates using properties with prefix "user1" from configuration file to initialize the same-named properties of the bean instance
// When using this bean, its name property will be Tom
@ConfigurationProperties(prefix = "user1")
public class User {
private String name;
// getter/setter methods omitted
}

Corresponding application.properties configuration file content:

user1.name=Tom

In this scenario, when the Bean is instantiated, @ConfigurationProperties matches properties after the corresponding prefix with the Bean object's properties. If conditions are met, values are assigned.

Scenario 2

Use @ConfigurationProperties and @Bean annotations on Bean definition methods in configuration classes. Using data source configuration as an example:

@Configuration
public class DataSourceConfig {

@Primary
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
}

Here, properties with prefix "spring.datasource.primary" are assigned to the corresponding DataSource property values.

In configuration classes annotated with @Configuration, the @Bean annotation on a method defines the returned object as a Bean and uses corresponding properties from the configuration file to initialize the Bean's properties.

Scenario 3

Use @ConfigurationProperties annotation on a regular class, then define it as a Bean through @EnableConfigurationProperties.

@ConfigurationProperties(prefix = "user1")
public class User {
private String name;
// getter/setter methods omitted
}

Here the User object doesn't use @Component-related annotations.

The corresponding usage of this User class:

@SpringBootApplication
@EnableConfigurationProperties({User.class})
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}

In the above code, when User is instantiated through @EnableConfigurationProperties, the @ConfigurationProperties functionality is used to match and assign properties.