Spring boot 的 properties 属性值配置 application.properties 与 自定义properties

  1. 配置属性值
    application.properties 文件直接配置:
    com.ieen.super.name="MDD"

    自定义properties文件配置:src/main/resources/conf/boot.properties

    com.ieen.boot.name="123"
    com.ieen.boot.value="456"
  2. 调用方法
    @Value 注解调用application.properties属性值:
    @Value("${com.ieen.super.name}")
    private String name;

    @Value注解调用自定义properties属性值:

    @PropertySource("classpath:conf/boot.properties")
    public class Main{
        @Value("${com.ieen.boot.name}")
        private String bootName;
    }
    注:@PropertySource 注解引入自定义properties从1.5以后才开始的
    // value 为自定义配置
    // ignoreResourceNotFound 默认false,文件不存在报错
    // encoding 设置编码
    // name 为Resource对象的beanname
    @PropertySource(value = { "classpath:boot.properties",
            "classpath:conf/boot.properties" }, ignoreResourceNotFound = false, encoding = "UTF-8", name = "boot-custom.properties")

    @ConfigurationProperties 配置properties属性对象:

    // spring boot 1.5以前的配置
    //@ConfigurationProperties(prefix = "com.ieen.boot",locations = "classpath:conf/boot.properties")
    @ConfigurationProperties(prefix = "com.ieen.boot")
    // 若是自定义properties则加上 @PropertySource(value = "classpath:conf/boot.properties", encoding = "UTF-8") @Component public class BootPropertiesBean { private String name; private String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
        @Autowired
        private BootPropertiesBean bean;

猜你喜欢

转载自www.cnblogs.com/aben-blog/p/8970251.html