@value和@ConfigurationProperties区别

1.区别


@ConfigurationProperties批量注入、支持松散语法绑定(person.Lats-name=person.LatsName)不支持spel、支持jsR303校验、支持复杂类型封装(key-value)

@value逐一注入、不支持松散语法绑定严格一致、支持spel、不持jsR303校验、不支持复杂类型封装(key-value)

就是他们的主要区别

2.@value的用法

package com.example.springdemo.entity;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.util.List;

@Component//把User加到容器中
@Data
public class User {
    /**
     * <bean class="User">
     *     <prrperty name="name" value="我们赋的值"></prrperty>
     *  </bean>
     */
    @Value("#{11+9}")
    private Long id;
    @Value("user.name")
    private String name;
    private Integer age;
    private List<Object>list;
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge(int i) {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    private String email;

    public Integer getAge() {
        return age;
    }

    public List<Object> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }
}

@value()括号中支持字面量、${}、从环境变量、配置文件中获取值、#{spel}等等方式

@@value就相当于 bean.xml文件中<bean>标签下的value的作用(看注释)

这次我们用application.properties配置文件做测试

这里的配置信息要通过包名.到属性 

测试代码

    @Autowired
    User user;
    @Test
    public void contextlodes(){
        System.out.println("测试结果输出:"+user);
    }

 结果

我们发现除了我们自己已经从@value赋值的其他属性都为空,证明的@value是逐一赋值

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值