SpringBoot配置

76 阅读1分钟

1.配置文件位置

默认名称application.properties,加载顺序:

1. 当前目录下的/config子目录
2. 当前目录
3. 一个classpath下的/config目录
4. classpath根路径(root)

Spring-boot配置文件的加载,先在与jar同级下查找,如果没有就去同级的config下查找;如果再没有,就在jar包中去查找相应的配置文件,如果再没有,就去jar包中的config下去查找。当查找到对应配置片段时,采用增量替换的方式来进行替换。

也可以自定义配置文件位置 java -jar xxxxx.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

2. 类文件加载配置方法

@Value("${""}")

结合@Configuration或者@Component等使用(是个bean)

@ConfigurationProperties(prefix="")

结合@Component或@SpringBootConfiguration使用 @ConfigurationProperties(prefix = "test", locations = classpath:xxxx.properties")

3. 多环境配置

Spring Profiles

一种是在application.properties中指定环境 spring.profiles.active = dev,database

一种是在运行jar包时指定 java -jar xxxxx.jar --spring.profiles.active=prod

4. 配置项校验

@Validated

@Validated
@SpringBootConfiguration
@ConfigurationProperties(prefix = "config")
public class EnvConfig {

    @NotEmpty(message = "配置项appId不能为空")
    private String appId;


    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }
}