Define custom @Required-style annotation in Spring
2024-10-14 10:34:41
The @Required
annotation 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-style
annotation for whatever reasons, Spring is allow you to define your custom @Required-style
annotation, which is equivalent to @Required
annotation.
In this example, you will create a custom @Required-style
annotation named @Mandatory
, which is equivalent to @Required
annotation.
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 @Mandatory
annotation 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-style
annotation named @Mandatory
, which is equivalent to @Required
annotation.
最新文章
- jQuery系列:五个模块总结
- 0526 Sprint1个人总结 &; 《构建之法》第八、九、十章
- python基础——使用元类
- 为Ubuntu笔记本电脑设置WiFi热点共享上网
- JavaScript 在页面上显示数字时钟
- dedecms后台上传图片附件返回302的问题
- 《图解密码技术》-chaper1-概述
- 数据结构(trie,启发式合并):HDU 5841 Alice and Bob
- 高仿QQ即时聊天软件开发系列之三登录窗口用户选择下拉框
- iOS控制器的创建方式
- ASP.NET之AdRotator实现淘宝浏览页面的商品随机推荐功能
- Android与JNI(二) ---- Java调用C++ 动态调用
- Vue.js根据列表某列值更新filter
- [Abp 源码分析]三、依赖注入
- 039 在weblogic下部署jndi的多数据源
- AngularJS资源合集[备忘]【申明:来源于网络】
- 【示例】Spring Quartz入门
- ES6学习笔记四:Proxy与Reflect
- POJ 1944 Fiber Communications (枚举 + 并查集 OR 线段树)
- Zabbix实战-简易教程--WEB类--Nginx
热门文章
- C#ShowCursor光标的显示与隐藏
- [51NOD1105]第k大的数(二分答案)
- git设置对比工具
- Parallel WebDriver executions using TestNG
- SharePoint的安装配置
- 添加gif效果图
- LeetCode Contains Duplicate (判断重复元素)
- dict 字典
- Vagrant搭建Ubuntu-JavaEE开发环境——Tomcat+JDK+MySQL+dubbo+测试
- sharepoint 2010 在aspx 写lambda 时错误