Spring Boot 获取配置文件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhaolinxuan1/article/details/83085335

1.yml增加配置

注意:冒号后面一定要有一个空格

company:
  name: 天霸
  address: 北京市海淀区

2.编写测试类

(1)通过value获取


    @Value("${company.name}")
    private String name;
    @Value("${company.address}")
    private String address;

    @RequestMapping("/testValue")
    public String getCompany(){
        return "name:"+name+";address:"+address;
    }

(2)基于properties获取

      写CompanyConstantk类

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

@Component
@ConfigurationProperties(prefix = "company")//获取配置名称

public class CompanyConstant {

    private String name;

    private String address;

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

    public String getName(){
        return name;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getAddress() {
        return address;
    }
}

获取属性值

 @Autowired
    private CompanyConstant companyConstant;
    @RequestMapping("/testProperties")
    public String getCompanyByProperties(){
        return  "通过Properties文件获取的》》》》"+"name:"+companyConstant.getName()+";address:"+companyConstant.getAddress();
    }

3.完整代码

@RestController
public class TestController {
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);
    
    //获取属性值
    @Value("${company.name}")
    private String name;
    @Value("${company.address}")
    private String address;

    @RequestMapping("/testValue")
    public String getCompany(){
        return "通过value获取的》》》》"+"name:"+name+";address:"+address;
    }

    @Autowired
    private CompanyConstant companyConstant;//注入配置类

    @RequestMapping("/testProperties")
    public String getCompanyByProperties(){
        return  "通过Properties文件获取的》》》》"+"name:"+companyConstant.getName()+";address:"+companyConstant.getAddress();
    }
}

4.测试结果

 

展开阅读全文

没有更多推荐了,返回首页