Spring自定義@Required-style注解

@Required注解是用來確保特定屬性已設置。如果您遷移現有專案到Spring框架或有自己的@Required-style注解不管是什麼原因,Spring允許您定義自定義@Required-style注解,相當於@Required注解。
在這個例子中,您將創建一個名為 @Mandatory 定制 @Required-style 注解,相當於@Required注解。

1.創建@Mandatory介面

package com.xuhuhu.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.xuhuhu.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.xuhuhu.common.Mandatory"/>
</bean>

	<bean id="CustomerBean" class="com.xuhuhu.common.Customer">
		<property name="action" value="buy" />
		<property name="type" value="1" />
	</bean>

</beans>

4. 完成

這樣做,創建了一個新的自定義命名 @Required-style的@Mandatory 注解,相當於 @Required 注解。

上一篇: Spring使用@Required注解依賴檢查 下一篇: Spring Bean InitializingBean和DisposableBean實例