自定义属性资源配置
大约 1 分钟
自定义属性资源配置
springboot 读取application.yml配置中信息的三种方式
application.yml配置信息:
user:
age: 18
username: immc
sexs: "男"
第一种方式
通过@Value("${user.age}") 注解获取方式
优点:单个使用方便,灵活性高
缺点:获取配置文件信息多,需要些大量的@Value,不利于开发,增加开发者的工作量
package com.example.springs.controller;
import com.example.springs.pojo.MyConfig;
import com.example.springs.pojo.Stu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class hello {
//通过注解获取application配置信息
@Value("${user.age}")
private Integer age;
@Value("${user.username}")
private String username;
@Value("${user.sexs}")
private String sexs;
@Autowired//注入其它类
private MyConfig myCustConfig;
@GetMapping("getMyCustConfig")
public Object getMyCustConfig(){
return username+age+sexs;
}
}
通过运行结果可以看出我们已经通过第一种方式获取到了里面的值:

第二种方式
通过@ConfigurationProperties(prefix = "demo.user")配置类的形式创建一个实体类
需要在pom.xml中配置依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
@Data
@Component
//这里的user只的是获取application.yml中的数据
@ConfigurationProperties(prefix = "user")
public class Demo {
private String username;
private String age;
private String sexs;
}
@RestController
public class TestController {
@Autowired
private Demo demo;
/**
* 通过创建实体类配置ConfigurationProperties的方式获取application配置的值
* @return
*/
@GetMapping("/testThree")
public Map<String, Object>test3(){
Map<String,Object> map = new HashMap();
map.put("name",demo.getUsername());
map.put("age",demo.getAge());
map.put("sexs",demo.getSexs());
return map;
}
}
参数较多,通过Map集合的方式接受多个参数:
