Preface
I believe that many people choose Spring Boot mainly because it can take into account the powerful functions of Spring and also achieve the convenience of rapid development. This article mainly introduces to you the relevant content about loading external configuration files when spring boot is started. I won’t say much below, let’s learn and learn with the editor.
Business Requirements:
Load external configuration files, making it easier to change during deployment.
First upload the code:
@SpringBootApplicationpublic 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(); }}Tools using variables
@Componentpublic 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); }} It can also be used via @Value("${key}")
The loading method has high priority. If the same name as the spring boot configuration file, the configuration in the application.properties file will be overwritten.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.