springboot学习笔记(3)
springboot引入外部配置文件
SpringBoot 的默认配置文件是 application.yml 或者 application.properties,接下来介绍引入其他的 properties 文件 或者 yml 文件的做法。
1、properties 文件
properties 文件引入较为简单,跟 Spring 一样。在配置类上使用 @PropertySource 注解引入,在其他地方使用 @Value 注解读取。
2、yml 文件
先从 SpringBoot 的默认配置文件 application.yml 文件开始,application.yml 的文件内容,是可以通过 @Value 的方式读取到的,比如 @Value("${server.port}") 这样。究其原因的话,应该是 SpringBoot 底层把 ApplicationContext 注册进 PropertySourcesPlaceholderConfigurer 所导致的
那么我们自定义的 yml 文件要怎么引入
1 @Bean 2 public PropertySourcesPlaceholderConfigurer properties() { 3 PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); 4 YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); 5 yaml.setResources(new ClassPathResource("my.yml")); 6 configurer.setProperties(yaml.getObject()); 7 return configurer; 8 }
这种方式,确实可以用,通过这种方式把 yml 文件加载到 PropertySourcesPlaceholderConfigurer 后,通过 @Value 方式读取到属性值。但是原来的 application.yml 中的 @Value 属性全获取不到了,所以不采用这种做法。
那要怎么加载我们自定义的 yml 文件呢?可以通过 YamlPropertiesFactoryBean 或者 YamlMapFactoryBean 类来加载
1 @Test 2 public void test() { 3 YamlPropertiesFactoryBean yml = new YamlPropertiesFactoryBean(); 4 yml.setResources(new ClassPathResource("my.yml")); 5 Properties properties = yml.getObject(); 6 Iterator<Map.Entry<Object, Object>> iterator = properties.entrySet().iterator(); 7 while (iterator.hasNext()) { 8 Map.Entry<Object, Object> entry = iterator.next(); 9 logger.info("YamlPropertiesFactoryBean 读取的配置文件内容是:{}-{}", entry.getKey(), entry.getValue()); 10 } 11 12 YamlMapFactoryBean yamlMapFactoryBean = new YamlMapFactoryBean(); 13 yamlMapFactoryBean.setResources(new ClassPathResource("my.yml")); 14 Map<String, Object> map = yamlMapFactoryBean.getObject(); 15 Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); 16 while (it.hasNext()) { 17 Map.Entry<String, Object> entry = it.next(); 18 logger.info("YamlPropertiesFactoryBean 读取的配置文件内容是:{}-{}", entry.getKey(), entry.getValue()); 19 } 20 }
另外需要提及的是 SpringBoot 还提供了 @ConfigurationProperties(prefix = "spring.datasource") 注解,将 yml 文件中的属性直接转换成 Bean 中的属性(前提是有 set 方法),而且属性的匹配很宽松,采用 Relaxed 绑定,以 firstName 举例(可匹配firstName、first-name、first_name、FIRST_NAME)。之后再在启动类中使用 @EnableConfigurationProperties(JavaConfig.class) 使之生效。
浙公网安备 33010602011771号