在Spring中定义自定义@Required样式注释

@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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值