spring boot启动时加载外部配置文件的方法
时间:2020-10-27 12:07:49|栏目:JAVA代码|点击: 次
前言
相信很多人选择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> T getProperty(String key, Class<T> targetType, T defaultValue) {
return environment.getProperty(key, targetType, defaultValue);
}
public static <T> T getProperty(String key, Class<T> 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文件中的配置。
总结
栏 目:JAVA代码
下一篇:Spring Security OAuth2 实现登录互踢的示例代码
本文标题:spring boot启动时加载外部配置文件的方法
本文地址:http://www.codeinn.net/misctech/16175.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




