引入配置文件
准备依赖,动态提示配置元数据信息
为了让 Spring Boot 更好的生成配置元数据文件,我们需要添加如下依赖(该依赖可以不添加,但是在 IDEA 和 STS 中不会有属性提示,没有提示的配置就跟用记事本一样),该依赖只会在编译时调用,所以不会对生产造成影响.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.0.1.RELEASE</version>
<optional>true</optional>
</dependency>
自定义配置属性
- application.properties中添加自定义的配置属性(固定的前缀)
- @ConfigurationProperties(prefix = "自定义前缀")标注自定义的配置类,属性字段与自定义的配置字段一一对应
application.properties文件
customer.p1=java
customer.p2=c++
自定义的配置类
@Component
@ConfigurationProperties(prefix = "customer")
public class MetaConfig {
private String p1;
private String p2;
public String getP1() {
return p1;
}
public void setP1(String p1) {
this.p1 = p1;
}
public String getP2() {
return p2;
}
public void setP2(String p2) {
this.p2 = p2;
}
}
自定义配置文件
- 自己命名一个配置文件xx.properties放在resources目录下
- @PropertySource("classpath:xx.properties")标注配置类对象,指向配置文件
customer.properties
customer.p1=java
customer.p2=c++
配置文件类
@Component
@PropertySource("classpath:customer.properties")
@ConfigurationProperties(prefix = "customer")
public class MetaConfig {
private String p1;
private String p2;
public String getP1() {
return p1;
}
public void setP1(String p1) {
this.p1 = p1;
}
public String getP2() {
return p2;
}
public void setP2(String p2) {
this.p2 = p2;
}
}
多环境配置(测试无效果)
在实际的开发中,可能在不同的环境有不同的配置文件。比如:生产、测试等;此时我们需要在application.properties文件中指定spring.profile.active属性,指定某个配置文件。而配置文件的格式必须为application-{activeName}.properties,application 为前缀不能改
- 自定义配置文件
- applicaiton.properties中指定激活哪个配置
application-dev.properties
server.servlet.context-path=/dev
application-test.properties
server.servlet.context-path=/test
激活,application.properties
spring.profile.active=dev