Before we go through the SpringBoot configuration file, let’s look at the annotations.
preface
I was trying to explain the SpringBoot configuration file, but I was confused by a lot of annotations that I found to be similar, such as @propertysource, @importResource, @Value, @con figurationProperties, etc. Plus @Configuration and @bean.
A configuration file, make so many comments, feel a bit big, this article is mainly on these comments for the eradication, I hope that after the eradication, I will not be afraid of them in the future.
Read the configuration based on XML
For the sake of the example, we create a configuration file jdbc.properties under package Resources:
jdbc.shop.url=jdbc:mysql://localhost:3104/xm_jointly? characterEncoding=utf8 jdbc.shop.username=louzai jdbc.shop.password=123456Copy the code
In the previous article “[MyBatis series 2] MyBatis integration with Spring”, we also have this configuration, but we use XML to read, and then need to configure file scan path in XML:
<! - used to load the configuration file - > < bean class = "org. Springframework. Beans. Factory. Config. Accomplished" > < property name="location"> <value>classpath:jdbc.properties</value> </property> </bean>Copy the code
Then read the configuration inside:
<! 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>
Copy the code
Now, is there a more elegant way to do this? You can keep going.
@ImportResource
The “used to load configuration files” section of the XML remains unchanged.
@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 (= JDBC url: mysql: / / localhost: 3104 / xm_jointly? characterEncoding=utf8, userName=louzai, passWord=123456)Copy the code
The configuration file is read by @importResource and then assigned to a member variable by @value. The use of @value can be seen later.
This approach still doesn’t feel very elegant, as it relies on XML configuration. Is there a way to get out of XML altogether? @propertysource comes into play.
@PropertySource & @Value
@PropertySource
This annotation @propertysource provides a convenient and declarative mechanism for the Environment in Spring. It is often used with Configuration, for example:
@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(a) {
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 = newAnnotationConfigApplicationContext(EnvironmentTest.class); EnvironmentTest connection = context.getBean(EnvironmentTest.class); connection.getData(); }}/ / output:
// url:jdbc:mysql://localhost:3104/xm_jointly? characterEncoding=utf8
// userName:louzai
// passWord:123456
Copy the code
@ComponentScan is used to scan EnvironmentTest beans, as described in the Article Spring Basics 3 common Annotations for Spring.
@propertysource is used to introduce an external property configuration and then work with the Environment to read the configuration.
@Value
Use Environment to read the configuration.
@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 = newAnnotationConfigApplicationContext(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)
Copy the code
Annotation directly via @value is also a common gesture in projects and highly recommended.
@value can also directly assign values to fields to get system properties, but I won’t expand it here, there’s a lot of information on the web.
This is an elegant way to read configuration data, but it’s still a bit cumbersome to assign each configuration data to @value. Is there a more elegant way? Enter @con figurationProperties.
@ Con fi gurationProperties
This is used to read yML configuration files in SpringBoot. Let’s look at reading configuration files one by one via @value.
Let’s create a new application.yml configuration:
shop: url: jdbc:mysql://localhost:3104/xm_jointly? characterEncoding=utf8 username: louzai password: 123456Copy the code
At sign 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(a) {
return "url:" + url + ", userName:" + userName + ", passWord:"+ passWord; }}Copy the code
This and the previous example is very like, just because SpringBoot automatically read application. Yml configuration, so you don’t have to specify the configuration file scanning path, start SpringBoot program, enter “http://localhost:8080/hello”, the output is as follows:
Through @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(a) {
return "url:" + url + ", username:" + username + ", password:"+ password; }}Copy the code
Start the service, the browser input “http://localhost:8080/hello2”, the output is as follows:
@Configuration & @Bean
This is commonly used in configuration file management classes to replace Bean injection in XML. This must be learned.
We usually combine the above configuration reading method, and then 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))))); }}Copy the code
This gives us a configuration class, EsConfig, in which RestHighLevelClient has already been injected into Spring via @Bean, which is a common implementation position for projects.
conclusion
Yesterday just accompanied his wife to see the animation of the fairy, feel this article is like the fairy, fairy level: refining gas → build base → Golden Dan → Yuan baby → change god → cross the hook (together) → to fairy → celestial fairy → too b fairy → Daluo jinxian → quasi saint → mixed daluo jinxian (saint) → Heaven road → avenue
- Gas refining: read configuration through XML;
This in the mi medium code, most or this way to read configuration.
- Base: XML is read with @importResource, but the reading of data values is moved to the object, that is, the member variables of the object are assigned with @Value.
If you still rely on XML to read the data, such as the old system code, you still need to use this, but fetching the value of the data configuration can be more elegant.
- Instead of XML, the configuration file can be read directly from @propertysource without XML transfer, but the configuration file data can be retrieved from Environment.
I feel like I don’t use this much anymore.
- Yuan Ying: Kill the Environment and use @value instead of @propertysource.
If you want to kill XML, just use this instead, which is the ultimate version of the Spring framework using configuration files.
- ConfigurationProperties: You can automatically associate configured data with the name of a class’s member variable instead of using @Value.
This is based only on SpringBoot, so it’s the ultimate version of the SpringBoot framework I’ve encountered so far.
- Carjacking: Combining @Configuration and @Bean, using Configuration classes, completely eliminates the dependency on XML Configuration by automatically reading data Configuration and then generating corresponding objects from these data Configuration items.
This can be used for Spirng and Spring Boot, and is a common configuration class generation posture in projects.
Afterword.
Before writing this article, I have been to posture, Java inside various reading configuration of circle, now after the carding, again recalling seen some program code, an instant feeling of six vein opened, the original project various reading configuration files, because the code version of the history reason, have to stay in the different stages of “cultivate immortality”.
This is why the cost of Learning Java is relatively high, just a configuration file to read so many versions, or miss the days of writing Go, simple and pure, there is no way, the current can only be rolled in Java this way.
Welcome everyone to like a lot, more articles, please pay attention to the wechat public number “Lou Zai advanced road”, point attention, do not get lost ~~