Preface
This article will focus on explaining the use of @PropertySource annotation in Spring and how to load the specified configuration file through PropertySource annotation. It also uses the PropertySource annotation and the @ConfigurationProperties annotations. I won’t say much below, let’s learn and study with the editor.
1.1. PropertySource annotation loads the specified property file
The Spring framework provides PropertySource annotation, with the purpose of loading the specified property file. Next, let's take a look at how to use this annotation. First we define a configuration class and add PropertySource annotation to the class as follows:
@Component@PropertySource(value= {"classpath:config/jdbc-bainuo-dev.properties"},ignoreResourceNotFound=false,encoding="UTF-8",name="jdbc-bainuo-dev.properties",)public class CustomerDataSourceConfig1 {private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "CustomerDataSourceConfig{" + "url='" + url + '/'' + '}'; }} The purpose of the above code is to load jdbc-bainuo-dev.properties in the config file in the classpath path. Where encoding is used to specify the encoding used to read the property file, we usually use UTF-8; ignoreResourceNotFound means whether an error is reported when the specified configuration file does not exist, and the default is false; for example, the loading property file specified above is jdbc-bainuo-dev.properties . If the file does not exist, the program will not report an error when ignoreResourceNotFound is true. If ignoreResourceNotFound is false, the program will report an error directly. In actual project development, it is best to set ignoreResourceNotFound to false. The default value of this parameter is false.
The value value is to set the attribute file to be loaded, and multiple properties can be loaded at one time. The value of name we set is jdbc-bainuo-dev.properties . This value must be unique in Springboot environment, if not set, the value is: " class path resource [config/jdbc-bainuo-dev.properties] ".
Many people may be wondering why it is " class path resource [config/jdbc-bainuo-dev.properties] "? This involves the encapsulation class Resource in Spring for resource files. The value we configured above is " classpath:config/jdbc-bainuo-dev.properties ", so Spring found that it starts with classpath, so the end is using ClassPathResource subclass. If it starts with a file, the class you ends up using is FileSystemResource.
After understanding the Resource class described above. Let's make it clear again that if the name value is not set in @PropertySource, the generation rule of name value is: find the final encapsulated Resource subclass based on the value value, and then call the getDescription method in the specific Resource subclass instance object. The return value of the getDescription method is the final name value.
For example, the getDescription method in the ClassPathResource class is implemented as follows:
public String getDescription() { StringBuilder builder = new StringBuilder("class path resource ["); String pathToUse = path; if (this.clazz != null && !pathToUse.startsWith("/")) { builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); builder.append('/'); } if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } builder.append(pathToUse); builder.append(']'); return builder.toString();} The above name processing logic can be temporarily impressed, and the source code will be tracked in detail for explanation in the future.
1.2. PropertySource annotation loads the specified property file test
In the above, we set up the PropertySource annotation to load the "classpath:config/jdbc-bainuo-dev.properties" file. The directory structure of this file is shown in the figure below:
The content of the jdbc-bainuo-dev.properties file is as follows:
spring.datasource.shareniu.url=shareniu
The contents of the application.properties file are as follows:
spring.profiles.active=dev
In the above configuration file, the spring.profiles.active property configures the current environment used is dev. spring.datasource.shareniu.url is just an ordinary property and has no special meaning in itself.
Let’s start writing Springboot’s startup class as follows:
@SpringBootApplicationpublic class DemoApplication {public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(DemoApplication.class); ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args); CustomerDataSourceConfig1 customerDataSourceConfig = configurableApplicationContext .getBean(CustomerDataSourceConfig1.class); System.out.print(customerDataSourceConfig);}} Run the above code and the output of the program is as follows:
CustomerDataSourceConfig{url='null'} Strange, why is the url empty? Hasn't the PropertySource annotation already loaded the jdbc-bainuo-dev.properties file into the current environment? We might as well try to see if the spring.datasource.shareniu.url property in jdbc-bainuo-dev.properties can be obtained, and then verify from the side that the PropertySource annotation has loaded the jdbc-bainuo-dev.properties file into the current environment.
Modify the code of the above startup class as follows:
@SpringBootApplicationpublic class DemoApplication {public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(DemoApplication.class); ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args); CustomerDataSourceConfig1 customerDataSourceConfig = configurableApplicationContext.getBean(CustomerDataSourceConfig1.class); String property = configurableApplicationContext.getEnvironment().getProperty("spring.datasource.shareniu.url"); System.out.println(property); System.out.print(customerDataSourceConfig);}} Run the above code and the output of the program is as follows:
Shareniu
From the above code, we can see that PropertySource is indeed effective. So how do we automatically inject spring.datasource.shareniu.url property value into the url property in CustomerDataSourceConfig1 class?
1.3. PropertySource annotation reads the specified file and injects the properties into the configuration class
Spring provides @Value annotation to read out the attribute values in the configuration file and set them into the corresponding attributes. Here we learn how to use @Value annotation. The same is true for the two classes in the above text as examples for detailed explanations. First, you need to modify the CustomerDataSourceConfig1 class. The modification part is as follows:
@Component@PropertySource( name="jdbc-bainuo-dev.properties",value= {"classpath:config/jdbc-bainuo-dev.properties"},ignoreResourceNotFound=false,encoding="UTF-8")public class CustomerDataSourceConfig1 { @Value("${spring.datasource.shareniu.url}") private String url;} In the above class, the @Value annotation is added to the url field and the SPEL expression is specified as ${spring.datasource.shareniu.url} . Run the springboot boot class again and the output of the console is shareniu. It indicates that the injection of attribute values can indeed be done through @Value. However, one of the less friendly aspects of using the @Value annotation method is that when there are a large number of properties in the project for configuration, we need to add @Value annotation to the class fields one by one, which is really difficult, but we can solve this problem through the @ConfigurationProperties annotation provided by Springboot.
1.4. ConfigurationProperties annotation use
@ConfigurationProperties is a class-level annotation, and the specific usage is as follows:
@Component@ConfigurationProperties(prefix = "spring.datasource.shareniu") @PropertySource( name="jdbc-bainuo-dev.properties",value= {"classpath:config/jdbc-bainuo-dev.properties"},ignoreResourceNotFound=false,encoding="UTF-8")public class CustomerDataSourceConfig1 { private String url; } In the above code, the ConfigurationProperties annotation is added to the CustomerDataSourceConfig1 class, and the prefix of the property is spring.datasource.shareniu . In this way, when Springboot processes, it will scan all fields in the current class and search and assemble properties. For example, if we configure prefix = "spring.datasource.shareniu" , there is a url field in CustomerDataSourceConfig1 class, then the attribute that the url field needs to match is prefix+ field = spring.datasource.shareniu.url .
That's not only a question? What if the specified field does not find the attribute? This can be configured as follows:
@ConfigurationProperties(prefix = "spring.datasource.shareniu",ignoreUnknownFields=true,ignoreInvalidFields=true)
ignoreUnknownFields: Ignore unknown fields.
ignoreInvalidFields: Whether to ignore fields that failed to verify. How do you understand this? For example, if we configure a variable of string type in the configuration file, and the fields in the class are of type int, it will definitely report an error. If this happens, we can tolerate that property value needs to be configured to true. This parameter value defaults to false.
This article will explain here. In the subsequent article, we will explain how @PropertySource annotation can realize the reading of configuration files in different environments. Files in different environments are dynamically switched to read. PropertySource is not supported by default, so we need to expand the source code corresponding to this annotation.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.