[英]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注释。
包括<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>
包括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.