@ConfigurationProperties与EnableConfigurationProperties

首先呢,我们需要知道@ConfigurationProperties注解的作用。

@ConfigurationProPerties注解实现了配置文件和实体类的属性注入。

举例说明:

application.yml文件:

student:
  name: 小明

Student.java:


@ConfigurationProperties(prefix = "student")
public class Student {
    private String name;
    public Student() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

需要注意的是:@ConfigurationProperties一般标注在类上,对成员变量的赋值用到了seetter方法,若无setter方法,是无法注入成功的

另外,关于属性的注入。除了在类上标注@ConfigurationProPerties注解,还可以在成员变量上直接用@Value("${ }")来注入。并且这种方式不需要利用setter方法。

此时的Student类有没有注入容器中呢?如果容器中有Student类,利用spring的控制反转的特性:注入进spring容器的bean,可以直接利用注解互相注入。

@Configuration
public class Myconfig {
    @Autowired
    private Student student;
    public void  sout(){
        System.out.println(student.getName()+"****");
    }
}

控制台报错。student不满足依赖关系,也就是容器中为找到该bean.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myconfig': Unsatisfied dependency expressed through field 'student';

既然是为注入到容器中,那我们在student类上再添加一个@Component注解不就可以解决问题了么?这当然可以。
接下来上代码,这里就用一下属性注入的另一种方式:

@Component
public class Student {
    @Value("${student.name}")
    private String name;
    public Student() {
    }
    public String getName() {
        return name;
    }
}

配置类不做改变:

@Configuration
public class Myconfig {
    @Autowired
    private Student student;
    public void  sout(){
        System.out.println(student.getName()+"****");
    }
}

这一次。控制台成功打印信息:

小明****

但是呢。我们一般不直接在属性的实体类上添加@Component注解,至于原因,再说吧。
不用@Component注解,那么我们如何在Config这个bean中用到Student这个类中的属性值呢。
@EnableConfigurationProperties注解出现了。
student这个类,需要往哪个bean中注入,就在哪个类的上面添加@EnableConfigurationProperties注


@EnableConfigurationProperties({com.example.pojo.Student.class})
@Configuration
public class Myconfig {
    @Autowired
    private Student student;
    public void  sout(){
        System.out.println(student.getName()+"****");
    }
}

结果当然没有问题。

小明****

需要注意的是

@EnableConfigurationProperties不能单独使用,他的值是声明了@ConfigurationProperties注解的类的全限定类名。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值