• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

spring boot启动时加载外部配置文件的方法

java 搞代码 4年前 (2022-01-05) 60次浏览 已收录 0个评论

这篇文章主要给大家介绍了关于spring boot启动时加载外部配置文件的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

前言

相信很多人选择Spring Boot主要是考虑到它既能兼顾Spring的强大功能,还能实现快速开发的便捷。本文主要给大家介绍了关于spring boot启动时加载外部配置文件的相关内容,下面话不多说了,来随着小编一起学习学习吧。

业务需求:

加载外部配置文件,部署时更改比较方便。

先上代码:

 @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplicationBuilder springApplicationBuilder = new SpringApplicationBuilder(Application.class); springApplicationBuilder.web(true); Properties properties = getProperties(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addLast(new PropertiesPropertySource("micro-service", properties)); springApplicationBuilder.environment(environment); springApplicationBuilder.run(args); } private static Properties getProperties() throws IOException { PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); propertiesFactoryBean.setIgnoreResourceNotFound(true); Resource fileSystemResource = resolver.getResource("file:/opt/company/test.properties"); propertiesFactoryBean.setLocations(fileSystemResource); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } }

使用变量的工具类

 @Component public class EnvironmentUtil { private static Environment environment; @Autowired public void setEnvironment(Environment environment) { EnvironmentUtil.environment = environment; } public static  T getProperty(String key, Class targetType, T defaultValue) { return environment.getProperty(key, targetType, defaultValue); } public static  T getProperty(String key, Class targetType) { return environment.getProperty(key, targetType); } public static String getProperty(String key) { return environment.getProperty(key); } public static String getProperty(String key, String defaultValue) { return environment.getProperty(key, defaultValue); } public static Integer getInteger(String key, Integer defaultValue) { return environment.getProperty(key, Integer.class, defaultValue); } }

也可以通过@Value("${key}")使用

这中加载方法优先级很高,如果与spring boot配置文件同名,将覆盖application.properties文件中的配置。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参

来源gao!daima.com搞$代!码网

考学习价值,如果有疑问大家可以留言交流,谢谢大家对gaodaima搞代码网的支持。

以上就是spring boot启动时加载外部配置文件的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:spring boot启动时加载外部配置文件的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址