@Value和@ConfigurationProperties都是用于属性的注入(相当于spring中<bean id=" " class=" ”>-》注入到容器中)
ConfigurationProperties:告诉Spring Boot将本类中的所有属性和配置文件中相关的配置进行绑定;prefix:配置文件中哪个下面的所有属性进行映射】
Person类
@Component@ConfigurationProperties(prefix = "person")public class Person {private String lastName;private Integer age;private Boolean boss;private Date date;private Map<String,Object> map;private List<Object> list;private Student student;public Student getStudent() {return student;}public void setStudent(Student student) {this.student = student;}
application.properties或者(application.yml)
person.last-name=张三person.age=20person.date=2000/10/10person.boss=falseperson.map.k1=v1person.map.k2=v2person.list=a,b,cperson.student.name=lisiperson.student.age=13
2.两者的比较
如果我们只是在某个业务逻辑中获取一下配置文件中的某项值,就使用@Value
比如下面这段代码
@RestControllerpublic class ValueController {@Value("${person.last-name}")private String name;@RequestMapping("/sayHello")public String sayHello(){return "hello"+name;}}