100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Spring Boot-@Value获取值和@ConfigurationProperties获取值的比较

Spring Boot-@Value获取值和@ConfigurationProperties获取值的比较

时间:2022-08-24 21:21:34

相关推荐

Spring Boot-@Value获取值和@ConfigurationProperties获取值的比较

@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;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。