2016-04-27 12 views
1

Wenn ich eine Klasse wie folgt:Frühling Anmerkungen: Warum @Required funktioniert nicht, wenn Klasse @Autowired ist

public class MyConfig { 
    private Integer threshold; 

    @Required 
    public void setThreshold(Integer threshold) { this.threshold = threshold; } 
} 

Und ich benutze es wie folgt:

public class Trainer { 
    @Autowired 
    private MyConfig configuration; 

    public void setConfiguration(MyConfig configuration) { this.configuration = configuration; } 
} 

und initialisieren die Trainer in der xML-Kontext wie folgt:

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

Aus irgendeinem Grund die @Required Anmerkung gilt nicht, und der Kontext beginnt withou t ein Problem (Es sollte eine Ausnahme ausgelöst haben, die besagt, dass die Feldschwelle erforderlich ist ...).

Warum ist das ??

+0

Überprüfen Sie, ob Sie 'RequiredAnnotationBeanPostProcessor' konfiguriert haben. Andernfalls wird '@ Required' nicht gescannt. – sura2k

Antwort

3

Ich denke, Sie haben möglicherweise eine Konfiguration verpasst.

einfach die @Required Anmerkung Anwendung wird die Eigenschaft Prüfung nicht durchzusetzen, müssen Sie auch ein RequiredAnnotationBeanPostProcessor zu Kenntnis von der @Required Annotation in Bean-Konfigurationsdatei registrieren.

Der RequiredAnnotationBeanPostProcessor kann auf zwei Arten aktiviert werden.

  1. Fügen <context:annotation-config/>

    Frühling Kontext hinzufügen und in Bean-Konfigurationsdatei.

    <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. Fügen RequiredAnnotationBeanPostProcessor

    Sie ‚RequiredAnnotationBeanPostProcessor‘ direkt in Bean-Konfigurationsdatei.

<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

Ich verstehe nicht, warum ich diese Bean nur brauche, wenn @Autowired verwendet wird, aber es funktioniert! Vielen Dank. – user1028741