首页 > 代码库 > spring boot 读取 application.properties 初始化bean

spring boot 读取 application.properties 初始化bean

application.properties

bean1.hello = 你好~

bean2.name  = name
bean2.title = title

bean3.info[name]    = name
bean3.info[title]   = title
bean3.info[age]     = age

bean4.info[0] = name0
bean4.info[1] = name1
bean4.info[2] = name2
bean4.info[3] = name3

  

BeanController
@RestController
public class BeanController {

    @Value("${bean1.hello}")
    String bean1;

    @Resource
    Bean2 bean2;

    @Resource
    Bean3 bean3;

    @Resource
    Bean4 bean4;

    @RequestMapping("bean1")
    public String bean1() {
        return bean1;
    }

    @RequestMapping("bean2")
    public Bean2 bean2() {
        return bean2;
    }

    @RequestMapping("bean3")
    public Bean3 bean3() {
        return bean3;
    }

    @RequestMapping("bean4")
    public Bean4 bean4() {
        return bean4;
    }

}

  

Bean2.java
@ConfigurationProperties(prefix = "bean2")
@Component
public class Bean2 implements Serializable{
    public String name;
    public String title;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

  

Bean3.java
@ConfigurationProperties(prefix = "bean3")
@Component
public class Bean3 implements Serializable{
    private Map<String, String> info;

    public Map<String, String> getInfo() {
        return info;
    }

    public void setInfo(Map<String, String> info) {
        this.info = info;
    }
}

  

Bean4.java
@ConfigurationProperties(prefix = "bean4")
@Component
public class Bean4 implements Serializable{
    private List<String> info;

    public List<String> getInfo() {
        return info;
    }

    public void setInfo(List<String> info) {
        this.info = info;
    }
}

  



spring boot 读取 application.properties 初始化bean