springboot加载配置文件几种方式

一,springboot优势之一就是自动化配置

  开发过程中springboot自动读取application.properties和application.yaml,我们可以利用这一点实现配置读取

二,say nothing without codes

  1,@Value(),最常用的方式

  application.yaml

config: zhang

  使用:  

    @Value("${config}")
    private String config;

    
    @PostMapping("/index")
    public void say() {
        System.out.println(config);
        
    }

  输出:

 

   2,配置成实体

  以上用法有个缺点,当某个配置有过多属性,比如邮件,有名称,密码,地址等属性,Value过多,代码过于丑陋,那么实体就是个很好的解决方式

  

config2:
  name: demo1
  value: demoValue1
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "config2")
public class BeanConfig {
    public String name;
    public String value;

}
@RestController
public class Controller {

    @Autowired
    public BeanConfig config2;

    @PostMapping("/index")
    public void say() {
        
        System.out.println(config2);
        
    }
}

  输出:BeanConfig(name=demo1, value=demoValue1)

  3,进阶版,配置成Map

  

config3:
  -id1:
    name: demo1
    value: demoValue1
  -id2:
    name: demo2
    value: demoValue2
@Data
@Component
@ConfigurationProperties(prefix = "config3")
public class Config3 {

    private Map<String, String> id1 = new HashMap<>();
    private Map<String, String> id2 = new HashMap<>();

    public Map<String, String> getId1() {
        return id1;
    }

    public void setId1(Map<String, String> id1) {
        this.id1 = id1;
    }

    public Map<String, String> getId2() {
        return id2;
    }

    public void setId2(Map<String, String> id2) {
        this.id2 = id2;
    }
}
@RestController
public class Controller {

    @Autowired
    public Config3 config3;

    @PostMapping("/index")
    public void say() {
       
        System.out.println(config3);
    }
}

  输出:Config3(id1={name=demo1, value=demoValue1}, id2={name=demo2, value=demoValue2})

 

三,总结

  以上配置基本满足日常需求

如果第三种也是可以配置成动态的方式,配置List里新增配置项可以自动识别。  

config4:
  maillist:
    - enable: true
      name: demo1
      value: demoValue1
    - enable: true
      name: demo2
      value: demoValue2
    - enable: true
      name: demo3
      value: demoValue3
@Data
@Component
@ConfigurationProperties(prefix = "config4")
public class Config4 {
    private List<MailBean> mailList;
}


@Data
public class MailBean {
    public String name;
    public String value;
}
@RestController
public class Controller {

    @Autowired
    public Config4 config4;

    @PostMapping("/index")
    public void say() {
        System.out.println(config4);
    }
}

输出:Config4(mailList=[MailBean(name=demo1, value=demoValue1), MailBean(name=demo2, value=demoValue2), MailBean(name=demo3, value=demoValue3)])

posted @ 2020-09-06 09:45  superChong  阅读(4756)  评论(0编辑  收藏  举报