@Required批注用于确保已设置特定属性。 如果出于任何原因将现有项目迁移到Spring框架或拥有自己的@Required样式注释,则Spring允许您定义自定义@Required样式注释,该注释等效于@Required注释。
在此示例中,您将创建一个名为@Mandatory的自定义@Required
@Required-style
批注,它等效于@Required
批注。
1.创建@Mandatory界面
package com.mkyong.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.mkyong.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.注册
在'RequiredAnnotationBeanPostProcessor'类中包含新的@Mandatory注释。
<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.mkyong.common.Mandatory"/>
</bean>
<bean id="CustomerBean" class="com.mkyong.common.Customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean>
</beans>
4.完成
完成后,您刚刚创建了一个名为@Mandatory的新自定义@Required样式批注,它等效于@Required批注。
标签: 春天
翻译自: https://mkyong.com/spring/spring-define-custom-required-style-annotation/