Define custom @Required-style annotation in Spring
2015-08-21 16:50
609 查看
The
In this example, you will create a custom
@Requiredannotation is used to make sure a particular property has been set. If you are migrate your existing project to Spring framework or have your own
@Required-styleannotation for whatever reasons, Spring is allow you to define your custom
@Required-styleannotation, which is equivalent to
@Requiredannotation.
In this example, you will create a custom
@Required-styleannotation named
@Mandatory, which is equivalent to
@Requiredannotation.
1. Create the @Mandatory interface
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. Apply it to a property
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. Register it
Include your new@Mandatoryannotation in ‘
RequiredAnnotationBeanPostProcessor’ class.
<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. Done
Done, you just created a new custom@Required-styleannotation named
@Mandatory, which is equivalent to
@Requiredannotation.
相关文章推荐
- 在eclipse启动tomact没有问题,直接切到tomact启动问题出来了。
- 动态菜单----动态生成菜单和java反射机制的使用
- 在SSH整合过程中ClassCastException:xxx_$$_javassist_0 cannot be cast to javassist.util.proxy.Proxy
- java适配器模式
- eclipse乱码解决方法
- Java中char数组与字符串String类型的转换
- eclipse乱码解决方法
- Java在HBase数据库创建表
- 设计模式(java) 单例模式 单例类
- 设计模式(java) 单例模式 单例类
- JAVA学习篇--静态代理VS动态代理
- myeclipse调式与属性显示
- PackageManager.java中的方法resolveContentProvider的参数说明有误。
- Eclipse无提示的解决办法
- Eclipse汉化后怎么改回英文版(可切换中英文)
- 优化Myeclipse8.5
- Eclipse汉化后怎么改回英文版(可切换中英文)
- SpringMVC两种方式实现多文件上传
- Eclipse中使用Maven新建Web项目
- java设计模式之——代理模式