繁体   English   中英

Spring注释:当类是@Autowired时,为什么@Required不起作用

[英]Spring Annotations: Why @Required doesn't work when class is @Autowired

当我有一个课程如下:

public class MyConfig {
    private Integer threshold;

    @Required
    public void setThreshold(Integer threshold) { this.threshold = threshold; }
}

我用它如下:

public class Trainer {
    @Autowired
    private MyConfig configuration;

    public void setConfiguration(MyConfig configuration) { this.configuration = configuration; }
}

并在xml上下文中初始化Trainer,如下所示:

<bean id="myConfiguration" class="com.xxx.config.MyConfig">
        <!--<property name="threshold" value="33"/>-->
</bean>

由于某种原因,@ Required注释不适用,并且上下文开始没有问题(它应该抛出一个异常,说明需要字段阈值......)。

这是为什么??

我想你可能错过了配置。

简单地应用@Required注释不会强制执行属性检查,您还需要注册RequiredAnnotationBeanPostProcessor以了解bean配置文件中的@Required注释。

RequiredAnnotationBeanPostProcessor可以通过两种方式启用。

  1. 包括<context:annotation-config/>

    添加Spring上下文和bean配置文件。

     <beans ... xmlns:context="http://www.springframework.org/schema/context" ... http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" > ... <context:annotation-config /> ... </beans> 
  2. 包括RequiredAnnotationBeanPostProcessor

    直接在bean配置文件中包含' RequiredAnnotationBeanPostProcessor '。

 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM