2016-05-14 9 views
3

私はカスタム注釈で春の依存関係をチェックしています。私はJavaでカスタム注釈を作成しましたが、これをFIELDに適用しています。そのMETHOD上の作業ではなく、FEILDFIELDクラスのjava注釈が機能していません

私のカスタム注釈にはクラスがあるある

import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.FIELD) 
public @interface Mandatory { 
} 

私のターゲットクラスは次のとおりです。

public class Student { 
    @Mandatory 
    int salary; 

    public Student() { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 

    public int getSalary() { 
     return salary; 
    } 

    public void setSalary(int salary) { 
     this.salary = salary; 
    } 

} 

と私の春・コンフィギュレーション・ファイルは

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 

    <context:annotation-config /> 

    <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"> 
    <property name="requiredAnnotationType" value="com.spring.core.annotation.Mandatory"/> 
    </bean> 


<bean id="student" class="com.spring.core.annotation.Student"> 
    <!-- <property name="salary" value="200000"></property> --> 
</bean> 

</beans> 
です

私のアプリケーションクラスは

です
public class App { 

    public static void main(String[] args) { 
     ApplicationContext context= new ClassPathXmlApplicationContext("annotations.xml"); 
     Student stud= (Student)context.getBean("student"); 
     System.out.println(stud); 
    } 
} 

出力は次のとおりです。Student [salary=0]期待

:それはのJavaDocによると

答えて

3

を必要とsalary例外プロパティをスローする必要があり、RequiredAnnotationBeanPostProcessorは、プロパティのセッターメソッドを見て、プロパティ自体をフィールドではありません。

このBeanPostProcessorの存在の動機は、開発者がコンテナが依存性注入値の設定のためにチェックしなければならないことを示すために、任意のJDK 1.5アノテーションでセッター特性独自のクラスのに注釈を付けるようにすることです。

強調部分が少し混乱しているので、私はのためのRequiredAnnotationBeanPostProcessorチェックデフォルトの注釈である@Required注釈のJavaDoc、を見ることで確認しました。あなたは@Targetメタアノテーションの参照のみMETHOD(ないFIELD)ことに気付くべきであり、Javadocは次のことを言及:

「必要」されているような方法(通常はJavaBeanのsetterメソッド)をマーク:つまり、setterメソッドは、値を依存性注入するように設定する必要があります。

関連する問題