When writing the project code, we require a more flexible configuration, the modular integrated better. In Spring Boot project in order to meet the above requirements, we will be a large number of parameters in the configuration file application.yml application.properties or by @ConfigurationProperties
annotation, we can easily obtain these parameter values
Use @ConfigurationProperties configuration module
Suppose we are building a module to send mail. In the local test, we really do not want to send the message to the module, so we need a parameter to "switch" disable this feature. In addition, we want to configure a default theme for these messages, so that when we see the messages in your inbox, you can quickly determine by mail subject This is a test message
Application.properties create these parameters in the file: Uploading ... re-upload canceled
We can use @Value
annotations or the use of the Spring Environment
bean to access these properties, this is sometimes injected into the arrangement is cumbersome. We will use the more secure way ( @ConfigurationProperties
) to obtain these properties
Uploading ... re-upload canceled
@ConfigurationProperties
The basic usage is very simple: we provide a class with fields for each external attributes to be captured. Please note the following:
- Prefix defines which bind to the external attribute fields of the class
- The loose Spring Boot binding rules, class property name must match the name of the external properties
- We can simply use a value to initialize a field to define a default value
- The class itself can be private to a package
- Class field must have public setter methods
If we MailModuleProperties type bean injected into another bean, this bean can now access the values of those external configuration parameters of type-safe way.
However, we still need to let us know of Spring @ConfigurationProperties class exists to load it into the application context ( interview not know the difference between BeanFactory and the ApplicationContext? )
Activation @ConfigurationProperties
For Spring Boot, create a MailModuleProperties type of bean, we can add the following ways to use its context
First, we can make Component Scan scanning by adding notes to @Component dump failed to re-upload canceled
It is clear that only when the package is the class where the Spring @ComponentScan
annotation scanned to take effect, by default, the notes will be scanned in the main application class for all packet structure
Activation @ConfigurationProperties
For Spring Boot, create a MailModuleProperties type of bean, we can add the following ways to use its context
First, we can make Component Scan scanning by adding notes to @Component dump failed to re-upload canceled
It is clear that only when the package is the class where the Spring @ComponentScan
annotation scanned to take effect, by default, the notes will be scanned in the main application class for all packet structure