Usage and configuration of spring properties
Developers who do not understand the properties in spring may feel a little confused, mainly because there are many configuration methods and use methods.
This article is not a principle analysis or source code analysis article, but hopes to help readers better understand and use spring properties.
Use of properties
Readers of this article have all used spring. Let's take a look at how properties are used. There are several common uses in spring:
1. Use in XML configuration file
That is, the value in ${} is automatically replaced.
2. Use @ value injection
3. Obtain through environment
There is something to pay attention to in this method. Not all configuration methods support obtaining property values through the environment interface. The pro test can only be used when using the annotation @ propertysource, otherwise null will be obtained. As for how to configure, we will talk about it right away.
If it is the application of spring boot Properties registered, that's OK.
Properties configuration
We talked about how to use our configured properties, so how to configure them? Spring provides many configurations.
1. Configure through XML
The following is the most commonly used configuration method, which is written in many projects:
2. Configure through @ propertysource
The previous configuration through XML is very common, but if you also have an impulse to eliminate all XML configuration files, you should use the following methods:
Note that @ propertysource must be used with @ configuration here. I won't expand it.
3. PropertyPlaceholderConfigurer
If readers have seen this, they should not be surprised. Before spring 3.1, it was often used in this way:
Of course, we can also use the corresponding Java configuration version:
4. PropertySourcesPlaceholderConfigurer
When it comes to spring 3.1, propertysourcesplaceholderconfigurer is introduced, which is a new class. Note that the name of propertyplaceholderconfigurer is one more source than that of the previous propertyplaceholderconfigurer, and the package is also different. It is in the spring context package.
There is no difference in configuration:
Let's also have a Java configuration version:
Spring boot related
Spring boot is really a good thing. It feels great to use it out of the box. Here is a brief introduction to the relevant contents.
Quickly generate a spring boot project: https://start.spring.io/