Java注释在类字段上不起作用。

4

我正在使用自己创建的自定义注解检查Spring依赖项。我已经在Java中创建了一个自定义注解,并将其应用于FIELD字段。它可以在METHOD方法中运行,但不能在FEILD字段中运行。

我的自定义注解类如下:

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;
    }

}

我的Spring配置文件是

<?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);
    }
}

输出是:学生 [薪水=0] 预期:应该抛出异常,属性薪水是必需的。
1个回答

3
根据JavaDoc,RequiredAnnotationBeanPostProcessor会查看属性的setter方法,而不是属性字段本身。

存在这个BeanPostProcessor的原因是允许开发者使用任意JDK 1.5注释来注释自己类的setter属性,以指示容器必须检查依赖注入值的配置。

强调部分有点令人困惑,所以我通过查看@Required注释的JavaDoc进行了确认,这是RequiredAnnotationBeanPostProcessor检查的默认注释。您应该注意到@Target元注释只引用METHOD(不是FIELD),并且JavaDoc提到以下内容:
标记一个方法(通常是JavaBean的setter方法)为“必需”的:也就是说,该setter方法必须配置为使用值进行依赖注入。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接