spring boot启动时加载外部配置文件的方法
前言
相信很多人选择SpringBoot主要是考虑到它既能兼顾Spring的强大功能,还能实现快速开发的便捷。本文主要给大家介绍了关于springboot启动时加载外部配置文件的相关内容,下面话不多说了,来随着小编一起学习学习吧。
业务需求:
加载外部配置文件,部署时更改比较方便。
先上代码:
@SpringBootApplication
publicclassApplication{
publicstaticvoidmain(String[]args)throwsException{
SpringApplicationBuilderspringApplicationBuilder=newSpringApplicationBuilder(Application.class);
springApplicationBuilder.web(true);
Propertiesproperties=getProperties();
StandardEnvironmentenvironment=newStandardEnvironment();
environment.getPropertySources().addLast(newPropertiesPropertySource("micro-service",properties));
springApplicationBuilder.environment(environment);
springApplicationBuilder.run(args);
}
privatestaticPropertiesgetProperties()throwsIOException{
PropertiesFactoryBeanpropertiesFactoryBean=newPropertiesFactoryBean();
ResourcePatternResolverresolver=newPathMatchingResourcePatternResolver();
propertiesFactoryBean.setIgnoreResourceNotFound(true);
ResourcefileSystemResource=resolver.getResource("file:/opt/company/test.properties");
propertiesFactoryBean.setLocations(fileSystemResource);
propertiesFactoryBean.afterPropertiesSet();
returnpropertiesFactoryBean.getObject();
}
}
使用变量的工具类
@Component
publicclassEnvironmentUtil{
privatestaticEnvironmentenvironment;
@Autowired
publicvoidsetEnvironment(Environmentenvironment){
EnvironmentUtil.environment=environment;
}
publicstaticTgetProperty(Stringkey,ClasstargetType,TdefaultValue){
returnenvironment.getProperty(key,targetType,defaultValue);
}
publicstaticTgetProperty(Stringkey,ClasstargetType){
returnenvironment.getProperty(key,targetType);
}
publicstaticStringgetProperty(Stringkey){
returnenvironment.getProperty(key);
}
publicstaticStringgetProperty(Stringkey,StringdefaultValue){
returnenvironment.getProperty(key,defaultValue);
}
publicstaticIntegergetInteger(Stringkey,IntegerdefaultValue){
returnenvironment.getProperty(key,Integer.class,defaultValue);
}
}
也可以通过@Value("${key}")使用
这中加载方法优先级很高,如果与springboot配置文件同名,将覆盖application.properties文件中的配置。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下