前言
相信很多人選擇Spring Boot主要是考慮到它既能兼顧Spring的強大功能,還能實現快速開發的便捷。本文主要給大家介紹了關于spring boot啟動時加載外部配置文件的相關內容,下面話不多說了,來隨著小編一起學習學習吧。
業務需求:
加載外部配置文件,部署時更改比較方便。
先上代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@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(); } } |
使用變量的工具類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
@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
文件中的配置。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://segmentfault.com/a/1190000013197238