Spring自定义@Required-style注解
作者:-- 发布时间:2019-11-20
@required注解是用来确保特定属性已设置。如果您迁移现有项目到spring框架或有自己的@required-style注解不管是什么原因,spring允许您定义自定义@required-style注解,相当于@required注解。
在这个例子中,您将创建一个名为 @mandatory 定制 @required-style 注解,相当于@required注解。
1.创建@mandatory接口
package com.h3.common;
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.method)
public @interface mandatory {
}
2.应用它到属性
package com.h3.common;
public class customer
{
private person person;
private int type;
private string action;
@mandatory
public void setperson(person person) {
this.person = person;
}
//getter and setter methods
}
3.注册它
包函新@mandatory注释到“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">
<property name="requiredannotationtype" value="com.h3.common.mandatory"/>
</bean>
<bean id="customerbean" class="com.h3.common.customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean>
</beans>
4. 完成
这样做,创建了一个新的自定义命名 @required-style的@mandatory 注解,相当于 @required 注解。