Java Spring注释:为什么@Required不';当类为@Autowired时无法工作
当我有一节课时,如下所示:Java Spring注释:为什么@Required不';当类为@Autowired时无法工作,java,spring,autowired,spring-annotations,Java,Spring,Autowired,Spring Annotations,当我有一节课时,如下所示: public class MyConfig { private Integer threshold; @Required public void setThreshold(Integer threshold) { this.threshold = threshold; } } public class Trainer { @Autowired private MyConfig configuration; publ
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; }
}
<bean id="myConfiguration" class="com.xxx.config.MyConfig">
<!--<property name="threshold" value="33"/>-->
</bean>
我的用法如下:
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; }
}
<bean id="myConfiguration" class="com.xxx.config.MyConfig">
<!--<property name="threshold" value="33"/>-->
</bean>
并在xml上下文中初始化培训师,如下所示:
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; }
}
<bean id="myConfiguration" class="com.xxx.config.MyConfig">
<!--<property name="threshold" value="33"/>-->
</bean>
出于某种原因,@Required注释不适用,上下文启动时没有问题(它应该抛出一个异常,说明字段阈值是必需的…)
为什么会这样???我想你可能错过了一个配置 仅应用@Required注释不会强制该属性 检查时,您还需要注册 Required注释BeanPostProcessor了解@Required 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>
可以通过两种方式启用所需的AnnotationBeanPostProcessor。
在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>
检查您是否配置了所需的注释BeanPostProcessor。否则,
@Required
将不会被扫描。我不明白为什么我只在使用@Autowired时才需要这个bean,但它可以工作!谢谢