Spring Boot 配置文件之前缀属性注入

Spring Boot 配置文件之前缀属性注入
强烈推介IDEA2021.1.3破解激活,IntelliJ IDEA 注册码,2021.1.3IDEA 激活码  

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说Spring Boot 配置文件之前缀属性注入,希望能够帮助大家进步!!!

  • application.properties
## 家乡属性 Dev
home.province=广东
home.city=深圳
home.desc=: 我生活在 ${home.province} ${home.city}.

在这里插入图片描述

  • 属性类
package com.ghgcn.hello.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "home")
public class HomeProperties {


    private String province;

    private String city;

    private String desc;


    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "HomeProperties{" +
                "province='" + province + '\'' +
                ", city='" + city + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

  • controller中使用
@RestController
public class HelloController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private HomeProperties homeProperties;

    @GetMapping("/hello/home")
    public HomeProperties getHome(){
        logger.info(homeProperties.toString());
        return homeProperties;
    }
}
  • 启动访问

在这里插入图片描述

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18100

发表评论