Spring自定义@Required-style注解
@Required注解是用来确保特定属性已设置。如果您迁移现有项目到Spring框架或有自己的@Required-style注解不管是什么原因,Spring允许您定义自定义@Required-style注解,相当于@Required注解。 在这个例子中,您将创建一个名为 @Mandatory 定制 @Required-style 注解,相当于@Required注解。 1.创建@Mandatory接口 package com.yiibai.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.yiibai.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/sp
1.创建@Mandatory接口
package com.yiibai.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.yiibai.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.注册它
<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.yiibai.common.Mandatory"/> </bean> <bean id="CustomerBean" class="com.yiibai.common.Customer"> <property name="action" value="buy" /> <property name="type" value="1" /> </bean> </beans>
交流与评论