SpringBoot--加载配置文件
配置文件的位置
1.默认位置
SpringBoot的默认配置文件名称为application.properties,SpringBoot将从以下列表加载application.properties文件,并将它们添加到Spring Environment中:
- 部署时,jar包所在目录的/config子目录
- jar包所在目录
- classpath目录下的/config子目录
- classpath目录
这个列表是按照优先级排序的,如果存在多个重名的application.properties的话,列表中位置高的将覆盖位置低的。
2.自定义位置
如果不喜欢application.properties这个文件名或者需要自定义配置文件的位置,可以在启动SpringBoot应用的时候,传入一个spring.config.location参数,指定配置文件的位置和名称。例:
java -jar xxxx.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
上述例子加载了两个配置文件,分别是位于classpath目录下的default.properties和override.properties文件。
加载配置文件的属性
在配置文件application.properties中配置属性:
test.name = wahaha
test.age = 27
test.tel = 18800118888
1.@Component和@Value("${“xxx”}")
在类中获取配置文件的属性:
@Component
public class Configurations {
@Value("${test.name}")
private String name;
@Value("${test.age}")
private String age;
@Value("${test.tel}")
private Long tel;
// getter and setter
}
在类的域属性上通过@Value("${xxxx}")指定关联属性,SpringApplication会自动加载。
2.@ConfigurationsProperties(prefix=“test”)
在上述方法中,手动书写@Value还是比较繁重的工作,好在SpringBoot提供了更加简洁的方式–@ConfigurationsProperties(prefix=“test”)。
prefix指定了配置文件中属性的前缀是test,并按照属性名进行自动匹配。例如:
@Component
@ConfigurationProperties(prefix = "test")
public class Configuration {
private String name;
private String age;
private Long tel;
// setter getter
}
另外,@ConfigurationsProperties(prefix=“test”,locations=“xxx.properties”)可以指定配置文件的位置和名称
根据运行环境加载不同的配置
1.Profiles
Profiles提供了一种隔离应用程序配置的方式,并让这些配置只能在特定的环境下生效。在配置文件中,用spring.profiles.active属性来指定特定环境的配置文件。在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:
- application-dev.properties:开发环境
- application-test.properties:测试环境
- application-prod.properties:生产环境
至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。例如:
application.properties配置:spring.profiles.active = dev即指定application-dev.properties会被加载。
2.通过启动参数指定运行环境
通过命令启动:
java -jar xxxxx.jar --spring.profiles.active=prod
3.加载多个配置文件
例如:
spring.profiles.active = dev,database
等于告诉Spring Boot加载application-dev.properties和application-database.properties文件,从而实现多个配置文件的加载。