spring boot 读取 properties 到 bean

参考:http://www.fengyunxiao.cn

 

1. pom.xml 中添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

 

2. 在resources目录下添加 infor.properties 配置文件

info.height=123
info.weight=456

 

3. 添加 javabean,使用注解@ConfigurationProperties配置前缀,使用注解@PropertySource,设置关联的properties文件。

@Configuration
@ConfigurationProperties(prefix = "info")
@PropertySource(value = "classpath:info.properties")
public class MyInfo {
    private String height;
    private String weight;

    public String getHeight() {
        return height;
    }

    public String getWeight() {
        return weight;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "MyInfo{" +
                "height='" + height + '\'' +
                ", weight='" + weight + '\'' +
                '}';
    }
}

 

4. 在使用时使用注解@Autowired注入bean

@RestController
public class HelloController {

    @Autowired
    private MyInfo myInfo;

    @RequestMapping(value = "/getObject")
    public String getObject() {
        return myInfo.toString();
    }
}

 

5. 运行,打开浏览器,查看

 

参考:http://www.fengyunxiao.cn

 

posted @ 2018-08-04 17:27  亦寒2017  阅读(222)  评论(1编辑  收藏  举报