Springboot配置文件
配置文件位置
- 类路径下
- 类路径下直接config目录
- 当前工作目录
- 当前工作目录直接config目录
- 当前工作目录下的直接config目录下的直接子目录
后面的会覆盖前面的
使用spring.config.name修改配置文件名,默认情况下为application
使用spring.config.location修改配置文件位置,如果指定的位置是一个目录,以/结尾
$ java -jar myproject.jar --spring.config.name=myproject
$ java -jar myproject.jar --spring.config.location=\
optional:classpath:/default.properties,\
optional:classpath:/override.properties
optional表示可选,当文件不存在时,也不用管。
spring.config.location会覆盖默认的配置文件加载位置,如果想额外添加,使用spring.config.additional-location
以上三个配置Spring会从下面几个位置获取
- 操作系统环境变量
- Java System.getProperty
- 命令行参数
@SpringBootApplication
@ConfigurationPropertiesScan("com.rufeng.boot.config")
public class Main {
public static void main(String[] args) {
/* abcd.properties */
System.setProperty("spring.config.name", "abcd");
System.setProperty("spring.config.additional-location", "optional:classpath:/application.yaml");
SpringApplication application = new SpringApplication(Main.class);
application.setBannerMode(Banner.Mode.LOG);
application.addListeners(new StartListener());
application.run(args);
}
}
从配置文件向Bean注入属性
@Value
使用简单情况,属性注入位置较少等,详细使用看这篇@Value的骚操作
@ConfigurationProperties
Spring比较推荐的方式,在各种包的自动配置代码中,被大量使用
被@ConfigurationProperties注解的类或方法,必须为容器中的Bean,通常以下使用方式
- 在目标类上添加@Component(构造函数注入时不行)
- 其他类@EnableConfigrurationProperties
- 方法上@Bean(无法使用构造函数绑定)
- 使用@ConfigurationPropertiesScan
通过Setter注入
@Data
@Component
@ConfigurationProperties(prefix = "redis", ignoreUnknownFields = false)
@Validated
public class RedisProperties {
private Duration expiration;
@NotNull
private String key;
}
通常情况下上,我们的这些属性是不允许更改的,这样应该使用构造函数绑定
构造函数绑定
此时不能通过@Component、@Bean、@Import等注入容器,有两种办法
- 使用@EnableConfigrurationProperties
- 使用@ConfigurationPropertiesScan扫描到该类
如果需要默认值,可以使用@DefaultValue
@Getter
@ConstructorBinding
@ConfigurationProperties(prefix = "redis", ignoreUnknownFields = false)
@Validated
public class RedisProperties {
private final Duration expiration;
private final String key;
public RedisProperties(@DefaultValue("600s") Duration expiration, @NotNull String key) {
this.expiration = expiration;
this.key = key;
}
}
属性校验
同样支持@Validated注解进行校验,使用方法同参数校验
@Value vs @ConfigurationProperties
- 前者灵活绑定有限(驼峰、横线、大小写等,具体参考文档),后者灵活绑定
- 前者不支持元数据(开发工具代码提示需要元数据)
- 前者支持SpringEL表达式,后者不支持
Q.E.D.