如何将配置文件里的配置载入到配置类中去?
使用 @ConfigurationProperties 注解可以将 application.yml / application.properties 里的指定配置项与 Bean 绑定起来。
根据 prefix 来绑定配置文件中符合前缀的配置项,自动绑定到 Bean 中。
@ConfigurationProperties(prefix = "test")
1、配置项
以 application.yml 为例
test:age: 18name: 张三
2、配置类
package com.example.boot.config;import lombok.Data;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@ConfigurationProperties(prefix = "test")@Component@Datapublic class TestConfig {private String name;private Integer age;}
3、控制器
package com.example.boot.controller;import com.example.boot.config.TestConfig;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;@RestController@Slf4jpublic class TestController {@AutowiredTestConfig testConfig;@RequestMapping("/test/config")public Map testConfig() {Map<String, Object> map = new HashMap<>();map.put("code", 1);map.put("msg", "ok");map.put("data", testConfig);return map;}}
4、测试

