场景:
在以往的开发中,需要读取properties文件或者yml文件。然后将里面的属性一个个set到实体中。
在spring boot则可以“节省”这些步骤。
spring boot会自动读取classpath下的application.properties(当只有这个文件的时候)。
虽然同名文件不同目录下的读取顺序会有先后顺序,或者会被properties.yml等文件覆盖,这里均不考虑。毕竟在实际开发中会统一约定配置文件。
案例代码
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
application.properties
com.eblly=eblly
eblly.name=eblly
eblly.sex=man
Chapter0202Application.java
package com.eblly;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties({ConfigBean.class})
public class Chapter0202Application {
public static void main(String[] args) {
SpringApplication.run(Chapter0202Application.class, args);
}
}
@EnableConfigurationProperties
开启自动配置。
ConfigBean.java
package com.eblly;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author eblly
* @since 2017/11/18
*/
@ConfigurationProperties(prefix = "eblly")
public class ConfigBean {
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
@ConfigurationProperties
配置属性,会将properties中的eblly.name
和eblly.sex
注入到当前实体的变量中。
测试controller
IndexController.java
package com.eblly;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author eblly
* @since 2017/11/18
*/
@RestController
public class IndexController {
@Value("${com.eblly}")
private String name;
@Autowired
private ConfigBean configBean;
@RequestMapping("/")
public ConfigBean hello() {
System.out.println("===>" + name);
return configBean;
}
}
启动并访问http://localhost:8080/
网友评论