文件内容:
aaa.a1=aa1123
aaa.a2=aa2123
aaa.a3=aa3123
aaa.a4=aa4123
bussiness.properties文件内容:
bbbb.a1=bb1123
bbbb.a2=bb2123
bbbb.a3=bb3123
bbbb.a4=bb4123
在SpringBoot启动类上加载配置文件即可!
@SpringBootApplication
@PropertySource(value = {"test.properties","bussiness.properties"})
public class PropertyApplication {
public static void main(String[] args) {
SpringApplication.run(PropertyApplication.class, args);
}
}
读取数据的方式,与之类似!
@RestController
public class HelloController {
@Value("${aaa.a2}")
private String a2;
@Value("${bbbb.a1}")
private String bbbbA1;
@GetMapping("a2")
public String a2(){
return JSON.toJSONString(a2);
}
@GetMapping("bbbbA1")
public String bbbbA1(){
return JSON.toJSONString(bbbbA1);
}
}
如果我们只是在业务中需要用到自定义配置文件的值,这样引入并没有什么问题;但是如果某些自定义的变量,在项目启动的时候需要用到,这种方式会存在一些问题,原因如下:
翻译过来的意思就是说:
虽然在@SpringBootApplication上使用@PropertySource似乎是在环境中加载自定义资源的一种方便而简单的方法,但我们不推荐使用它,因为SpringBoot在刷新应用程序上下文之前就准备好了环境。使用@PropertySource定义的任何键都加载得太晚,无法对自动配置产生任何影响。
因此,如果某些参数是启动项变量,建议将其定义在application.properties或application.yml文件里面,这样就不会有问题!
或者,采用【自定义环境处理类】来实现配置文件的加载!
2.4、通过自定义环境处理类,实现配置文件的加载
实现方法也很简单,首先,创建一个实现自EnvironmentPostProcessor接口的类,然后自行加载配置文件。
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
//自定义配置文件
String[] profiles = {
"test.properties",
"bussiness.properties",
"blog.yml"
};
//循环添加
for (String profile : profiles) {
//从classpath路径下面查找文件
Resource resource = new ClassPathResource(profile);
//加载成PropertySource对象,并添加到Environment环境中
environment.getPropertySources().addLast(loadProfiles(resource));
}
}
//加载单个配置文件
private PropertySource<?> loadProfiles(Resource resource) {
if (!resource.exists()) {
throw new IllegalArgumentException("资源" + resource + "不存在");
}
if(resource.getFilename().contains(".yml")){
return loadYaml(resource);
} else {
return loadProperty(resource);
}
}
/**
* 加载properties格式的配置文件
* @param resource
* @return
*/
private PropertySource loadProperty(Resource resource){
try {
//从输入流中加载一个Properties对象
Properties properties = new Properties();
properties.load(resource.getInputStream());
return new PropertiesPropertySource(resource.getFilename(), properties);
}catch (Exception ex) {
throw new IllegalStateException("加载配置文件失败" + resource, ex);
}
}
/**
* 加载yml格式的配置文件
* @param resource
* @return
*/
private PropertySource loadYaml(Resource resource){
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource);
//从输入流中加载一个Properties对象
Properties properties = factory.getObject();
return new PropertiesPropertySource(resource.getFilename(), properties);
}catch (Exception ex) {
throw new IllegalStateException("加载配置文件失败" + resource, ex);
}
}
}