参考: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. 运行,打开浏览器,查看

spring boot 读取 properties 到 bean

 

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

 

相关文章:

  • 2021-10-29
  • 2022-02-08
  • 2022-02-08
  • 2021-09-02
猜你喜欢
  • 2022-02-08
  • 2022-02-19
  • 2019-12-24
  • 2022-03-03
  • 2022-02-08
  • 2021-11-16
  • 2022-02-08
相关资源
相似解决方案