当我上课时,如下所示:
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/>
在Bean配置文件中添加Spring上下文。
<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
RequiredAnnotationBeanPostProcessor
直接在bean配置文件中包含“ ”。
<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"/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句