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=20
person.date=2000/10/10
person.boss=false
person.map.k1=v1
person.map.k2=v2
person.list=a,b,c
person.student.name=lisi
person.student.age=13

2.两者的比较

@ConfigurationProperties@Value
不支持SpEL支持SpEL
支持JSR303校验不支持
-批量注入配置文件的属性--一个一个指定-
支持松散语法不支持
支持复杂类型 如:Map集合不支持

如果我们只是在某个业务逻辑中获取一下配置文件中的某项值,就使用@Value
比如下面这段代码

@RestController
public class ValueController {

    @Value("${person.last-name}")
    private String name;

    @RequestMapping("/sayHello")
    public String sayHello(){
        return "hello"+name;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Thecoastlines

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值