Spring Boot 配置自动读取属性或 YAML
原创2019/3/18大约 2 分钟
Spring Boot 配置自动读取属性或 YAML
1、认识两个注解:
@PropertySource:指定自定义属性文件的路径,注意只支持Properties文件@ConfigurationProperties:指定绑定属性的层级(可以加一个prefix参数表示一类前缀)
2、自动封装成实体类
2.1、约定
假设现在只存在 application.properties 文件:
jastar.demo.my-name=jastarwang2.2、示例代码代码
(1)使用方式一:指定全称
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.Getter;
@Getter
// 不用Setter因为直接设置到属性上了
@Component
@ConfigurationProperties
public class SystemConfig {
@Value("${jastar.demo.my-name}")
public String name;
}(2)使用方式二:自动驼峰
@Getter
// 需要Setter因为是通过调用set方法绑定的
@Setter
@Component
@ConfigurationProperties(prefix="jastar.demo")
public class SystemConfig {
// 自动映射成驼峰命名
public String myName;
}(3)使用方式三:静态属性
// 自己写Getter和Setter了
@ConfigurationProperties
public class SystemConfig {
public static String name;
@Value("${jastar.demo.my-name}")
public void setName(String _name){
name=_name;
}
public static String getName(){
return name;
}
}2.3、再自定义一个 Yaml 文件并读取
假设现在在之前情况下(已存在 properties 文件),再自定义一个或多个 yml 文件,那怎么读取并自动绑定呢?
注意:当 properties 文件和 yaml 文件同时存在时,properties 文件的优先级比较高,此时无法自动读取 yml 中的内容,需要进一步配置
Spring 中有两个类用来加载 Yaml 文件:YamlPropertiesFactoryBean 和 YamlMapFactoryBean;可以通过 PropertySourcePlaceholderConfigurer 来加载 Yaml 文件,暴露 Yaml 文件到 Spring 环境中:
@Configuration
public class WebConfig {
@Bean
public PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
// yaml.setResources(new FileSystemResource("your.yml"));//File引入
yaml.setResources(new ClassPathResource("your.yml"));// class引入
configurer.setProperties(yaml.getObject());
return configurer;
}
}此时,再通过 @Value 的形式即可取到值!

