springboot版本2.1.0.RELEASE
依賴
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
配置文件
application.yml
spring:
profiles:
include: test
demo:
config:
test: test-demo.yml
dev: dev-demo.yml
production: pro-demo.yml
application-test.properties
demo.lee.test=test.demo.properties
demo.lee.dev=dev.demo.properties
demo.lee.production=production.demo.properties
application-dev.properties
test=test.dev.properties
dev=dev.dev.properties
production=production.dev.properties
在springboot中注入使用配置文件中的數(shù)據(jù)主要有以下三種方式
- @Value注解
- @ConfigurationProperties注解和@EnableConfigurationProperties注解配合使用
- @PropertySource注解
@Value注解
IndexController.class
@RestController
public class IndexController {
@Value("${demo.lee.test}")
String test;
@Value("${demo.config.dev}")
String dev;
@RequestMapping("/")
public String indexController() {
return test + " " + dev;
}
}
// 返回test.demo.properties dev-demo.yml
@ConfigurationProperties注解和@EnableConfigurationProperties注解搭配使用
EnvConfig.class
@ConfigurationProperties(prefix = "demo.config")
public class EnvConfig {
private String test;
private String dev;
private String production;
// 注意必須存在setter咪惠,否則會(huì)注入失敗
/** setter and toString **/
}
IndexController.class
@RestController
public class IndexController {
@Autowired
EnvConfig envConfig;
@RequestMapping("/en")
public String entityController() {
return envConfig.toString();
}
}
// 返回EnvConfig{test='demo.yml', dev='dev-demo.yml', production='pro-demo.yml'}
@PropertySource注解
PropertyConfig.class
@Configuration
@PropertySource("classpath:application-dev.properties")
// 必須指定前綴退子,否則注入不進(jìn)來(lái)诞丽,prefix可以使空字符串磅轻,編譯器可能會(huì)報(bào)錯(cuò)
// 但運(yùn)行不報(bào)錯(cuò)
@ConfigurationProperties(prefix = "")
public class PropertyConfig {
private String test;
private String dev;
private String production;
/** getter、setter和toString **/
}
IndexController.class
@RestController
public class IndexController {
@Autowired
PropertyConfig propertyConfig;
@RequestMapping("/pro")
public String propertyController() {
return propertyConfig.toString();
}
}
// 返回PropertyConfig{test='test.dev.properties', dev='dev.dev.properties', production='production.dev.properties'}