Spring自定义@Required-style注解

@Required注解是用来确保特定属性已设置。如果您迁移现有项目到Spring框架或有自己的@Required-style注解不管是什么原因,Spring允许您定义自定义@Required-style注解,相当于@Required注解。
在这个例子中,您将创建一个名为 @Mandatory 定制 @Required-style 注解,相当于@Required注解。

1.创建@Mandatory接口

package com.zyiz.netmon;

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.zyiz.netmon;

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.zyiz.netmon.Mandatory"/>
</bean>
	
	<bean id="CustomerBean" class="com.zyiz.netmon.Customer">
		<property name="action" value="buy" />
		<property name="type" value="1" />
	</bean>
	
</beans>

4. 完成

这样做,创建了一个新的自定义命名 @Required-style的@Mandatory 注解,相当于 @Required 注解。

上一篇:Spring使用@Required注解依赖检查

下一篇:Spring Bean InitializingBean和DisposableBean实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程