欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 读取application.yml自定义配置文件

程序员文章站 2022-03-02 18:13:37
...

(1)引入依赖包

<!--读取资源文件依赖-->
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

(2)application.yml自定义配置

employee :
   salary: 2000
   title: programer

(3)创建自定义字段bean

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

@Component
@ConfigurationProperties(prefix = "employee")
public class EmployeeApplicationUnt {

    private String salary;
    private String title;


    public String getSalary() {
        return salary;
    }

    public void setSalary(String salary) {
        this.salary = salary;
    }

    public String getTitle() {
        return title;
    }

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

(4)测试获取资源文件中的值

 @Autowired
    private  EmployeeApplicationUnt salar;

 @RequestMapping("/getEmp")
    public String getEmp(){

        return salar.getSalary();
    }

浏览器打开已经获取到值了