2016-04-27 46 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