2016-04-27 79 views
1

当我有一个类,如下所示为什么@Required不起作用:Spring注解:当类@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上下文如下:

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

出于某种原因@Required注解不适,和上下文开始withou这是一个问题(它应该抛出一个异常说明字段阈值是必需的......)。

为什么?

+0

检查您是否已经配置'RequiredAnnotationBeanPostProcessor'。否则'@必需的'将不会被扫描。 – sura2k

回答

3

我想你可能错过了一个配置。

简单应用@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"/> 
+0

我不明白为什么只有在使用@Autowired时才需要这个bean,但它的工作原理!谢谢。 – user1028741