我正在用自定义注释检查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;
}
}
我的弹簧配置文件是
<?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]
预期:它应该抛出异常属性salary
必需的
根据JavaDoc,RequiredAnnotationBeanPostProcessor
查看属性setter方法,而不是属性字段本身。
这个BeanPostProcessor存在的动机是允许开发人员使用任意JDK 1.5注释来注释他们自己类的setter属性,以表明容器必须检查依赖项注入值的配置。
强调的部分有点令人困惑,所以我通过查看@Required
注释JavaDoc来确认,这是RequiredAnnotationBeanPostProcessor
检查的默认注释。您应该注意到,@Target
元注释只引用METHOD(而不是FIELD),JavaDoc提到了以下内容:
将一个方法(通常是JavaBean setter方法)标记为"必需":也就是说,必须将setter方法配置为注入值的依赖项。