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

前言

创新互联长期为上千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为自贡企业提供专业的做网站、网站制作,自贡网站改版等技术服务。拥有10年丰富建站经验和众多成功案例,为您定制开发。

相信很多人选择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文件中的配置。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对创新互联的支持。


文章题目:springboot启动时加载外部配置文件的方法
文章网址:http://hxwzsj.com/article/jichsp.html

其他资讯

Copyright © 2025 青羊区翔捷宏鑫字牌设计制作工作室(个体工商户) All Rights Reserved 蜀ICP备2025123194号-14
友情链接: 成都定制网站建设 重庆手机网站建设 专业网站设计 网站建设方案 成都网站制作 成都品牌网站建设 外贸营销网站建设 企业网站设计 手机网站制作 成都网站建设 成都网站设计 手机网站制作设计 成都网站建设公司 成都网站制作 企业网站制作 成都网站建设公司 外贸网站建设 网站建设开发 营销型网站建设 成都网站建设 企业网站设计 成都网站设计