Before explaining the SpringBoot configuration file, let's first learn the relevant annotations for reading the configuration file. This article will take you through all of them!
preface
Originally, I wanted to explain the Configuration file of SpringBoot, but a bunch of annotations in it made me feel that they are almost the same, such as @ PropertySource, @ ImportResource, @ Value, @ Con "gurationProperties, plus @ Configuration and @ Bean.
A configuration file with so many annotations feels a little big. This article is mainly about literacy of these annotations. I hope I won't be afraid of them after literacy.
Read configuration based on XML
To facilitate the explanation of the example, we create a configuration file JDBC. Net under the package resources properties:
jdbc.shop.url=jdbc:mysql://localhost:3104/xm_jointly?characterEncoding=utf8 jdbc.shop.username=louzai jdbc.shop.password=123456
Previously, in the article [MyBatis Series 2] integration of MyBatis and Spring, we also have this configuration, but we read it in XML, and then we need to configure the file scanning path in XML:
<!-- Used to load configuration files --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:jdbc.properties</value> </property> </bean>
Then the configuration can be read:
<!-- Define data source --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${jdbc.shop.url}"></property> <property name="username" value="${jdbc.shop.username}"></property> <property name="password" value="${jdbc.shop.password}"></property> </bean>
So is there a more elegant implementation? You can continue to look below.
@ImportResource
The "used to load configuration file" in XML remains unchanged. See the example directly:
@ImportResource("classpath:applicationContext.xml") public class ImportResourceTest { @Value("${jdbc.shop.url}") private String url; @Value("${jdbc.shop.username}") private String userName; @Value("${jdbc.shop.password}") private String passWord; public static void main(String args[]) { ApplicationContext context = new AnnotationConfigApplicationContext(PropertySourceTest.class); PropertySourceTest connection = context.getBean(PropertySourceTest.class); System.out.println(connection.toString()); } } //Output: // PropertySourceTest(url=jdbc:mysql://localhost:3104/xm_jointly?characterEncoding=utf8, userName=louzai, passWord=123456)
Read the configuration file through @ ImportResource and assign @ Value to the member variable. You can continue to look at the usage of @ Value later.
This method is still not elegant, because it still depends on XML configuration. Is there a way to completely break away from XML, @ PropertySource will appear.
@PropertySource & @Value
@PropertySource
This annotation @ PropertySource provides convenience and declaration mechanism for the Environment in Spring. It is usually used together with Configuration. See the example directly:
@ComponentScan({"com.java.annotation.spring.bean.fileconfig"}) @Component @PropertySource("classpath:jdbc.properties") public class EnvironmentTest { @Resource Environment environment; private String url; private String userName; private String passWord; public void getData() { url = environment.getProperty("jdbc.shop.url"); userName = environment.getProperty("jdbc.shop.username"); passWord = environment.getProperty("jdbc.shop.password"); System.out.println("url:" + url); System.out.println("userName:" + userName); System.out.println("passWord:" + passWord); } public static void main(String args[]) { ApplicationContext context = new AnnotationConfigApplicationContext(EnvironmentTest.class); EnvironmentTest connection = context.getBean(EnvironmentTest.class); connection.getData(); } } //Output: // url:jdbc:mysql://localhost:3104/xm_jointly?characterEncoding=utf8 // userName:louzai // passWord:123456
@ComponentScan is used to scan the bean s of EnvironmentTest. For details, please refer to the article [Spring Foundation Series 3] notes commonly used in spring.
@PropertySource is used to introduce external property configuration, and then read the content of the configuration in combination with the Environment. This example can be understood at a glance. So Easy!
@Value
It's troublesome to read the configuration with Environment. Is there a simpler way? Look at the example directly:
@ComponentScan({"com.java.annotation.spring.bean.fileconfig"}) @Component @PropertySource("classpath:jdbc.properties") @ToString public class PropertySourceTest { @Value("${jdbc.shop.url}") private String url; @Value("${jdbc.shop.username}") private String userName; @Value("${jdbc.shop.password}") private String passWord; public static void main(String args[]) { ApplicationContext context = new AnnotationConfigApplicationContext(PropertySourceTest.class); PropertySourceTest connection = context.getBean(PropertySourceTest.class); System.out.println(connection.toString()); } } //Output: // DBConnection(url=jdbc:mysql://localhost:3104/xm_jointly?characterEncoding=utf8, userName=louzai, passWord=123456)
Mark directly through @ Value, which is also a commonly used pose in the project. It is strongly recommended.
@Value can also directly assign values to fields to obtain system properties, which will not be expanded here. There are many online materials.
This way of reading configuration feels very elegant, but each configuration data needs to be assigned through @ Value, which is still a little troublesome. Is there a more elegant way@ Con "gurationProperties is on the stage.
@ConfigurationProperties
This is used to read the yml configuration file in SpringBoot. Let's first look at the way to read the configuration one by one through @ Value.
Let's create a new application YML configuration:
shop: url: jdbc:mysql://localhost:3104/xm_jointly?characterEncoding=utf8 username: louzai password: 123456
By @ Value
@Service @RequestMapping public class HelloWorld { @Value("${shop.url}") private String url; @Value("${shop.username}") private String userName; @Value("${shop.password}") private String passWord; @ResponseBody @RequestMapping("/hello") public String test() { return "url:" + url + ", userName:" + userName + ", passWord:" + passWord; } }
This is similar to the previous example, only because SpringBoot will automatically read the application YML configuration, so there is no need to specify the configuration file scanning path. After starting the SpringBoot program, enter“ http://localhost:8080/hello ”, the output is as follows:
By @ ConfigurationProperties
@Service @RequestMapping @Setter @ConfigurationProperties(prefix = "shop") public class HelloWorld2 { private String url; private String username; private String password; @ResponseBody @RequestMapping("/hello2") public String test() { return "url:" + url + ", username:" + username + ", password:" + password; } }
After starting the service, enter“ http://localhost:8080/hello2 ”, the output is as follows:
@Configuration & @Bean
This class is commonly used for configuration file management and is used to replace Bean injection in XML. This must be mastered. For details, please refer to the article [Spring Foundation Series 3] notes commonly used in spring
We will generally combine the above configuration reading methods and generate the corresponding configuration class:
@Configuration @PropertySource("classpath:es.properties") public class EsConfig { @Value("${es.hostname}") private String hostname; @Value("${es.port}") private String port; @Bean public RestHighLevelClient client() { return new RestHighLevelClient(RestClient.builder(new Node(new HttpHost(hostname, Integer.parseInt(port))))); } }
In this way, we can get a configuration class EsConfig. RestHighLevelClient in the configuration class has completed Spring injection through @ Bean, which is also a common implementation gesture in the project.
summary
I just watched the animation of cultivating immortality with my wife yesterday. I feel that this article is like cultivating immortality. The level of cultivating immortality is: refining Qi → building foundation → golden elixir → Yuanying → transforming God → crossing robbery (Hedao) → earth immortality → heavenly immortality → golden immortality → Taiyi golden immortality → great Luo Jinxian → quasi Saint → mixed Yuan great Luo Jinxian (SAGE) → heavenly way → Avenue
-
Gas refining configuration: read by XML;
In the code of Xiaomi Zhongtai, most of them still read the configuration in this way.
-
Foundation building: the XML is read through @ ImportResource, but the part of the read data Value is moved to the object, that is, the member variable of the object is assigned with @ Value.
If you still rely on XML to read data, such as old system code, you still need to use it. Just get the value of the data configuration, which can be more elegant.
-
Jindan: kill the XML and directly read the data configuration file through @ PropertySource without XML transfer, but the configuration file data is obtained by Environment.
I feel this is rarely used.
-
Yuanying: kill the Environment and directly replace it with @ Value. This is still used in combination with @ PropertySource.
If you want to kill XML, just use this instead. This is the ultimate version of the configuration file used by the Spring framework.
-
Huashen: XML has been eliminated, and @ Value is not replaced one by one. Directly through @ ConfigurationProperties, the configured data is automatically associated with the member variable name of the class.
This is only based on SpringBoot, so it is also the ultimate version of the SpringBoot framework configuration file I have encountered so far.
-
Rescue: combine @ Configuration and @ Bean, use the Configuration class, automatically read the data Configuration, and then generate the corresponding objects through these data Configuration items, so as to completely get rid of the dependence on XML Configuration.
This can be used for Spirng and Spring Boot. It is also a common configuration class generation pose in projects.
Postscript
Before writing this article, I have been making a circle about various posture of reading configuration in Java. Now after combing it, I think back to some project codes I have seen before. I instantly feel that Ren Tong's six veins have been opened up. The original ways of reading configuration files in the project remain in different stages of "cultivating immortality" because of the historical version of the code.
This is why the learning cost of Java is relatively high. There are so many versions for reading a configuration file. I still miss the days when I wrote Go. It's simple and pure. There's no way. At present, I can only be rolled up on the road of Java.
Welcome to the many more articles, please pay attention to the official account of WeChat public, "the road of Lou Tsai", pay attention to it and not lose your way.