Creating Custom @Required with Spring

To create a custom Required annotation, You will need to ensure that your custom annotation type is itself annotated with appropriate annotations for its target and runtime retention policy.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml


1. Creating Mandatory Interface

Create a custom @Required Annotation named @Mandatory

package com.kruders.bean;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public @interface Mandatory {


Now create Employee Class as following. Use Mandatory Annotation on setters.

package com.kruders.bean;

public class Employee {
    private String name;
    private String age;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String getAge() {
        return age;
    public void setAge(String age) {
        this.age = age;

3. Configuration

Create Spring-Bean.xml and write the following code

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
		<property name="requiredAnnotationType" value="com.kruders.bean.Mandatory"/>
    <bean id="employee" class="com.kruders.bean.Employee">
        <property name="name" value="Puneet" />
    <property name="age" value="22" />

4. Run Program

Create class that displays the employee and address details and run it as Java Application

package com.kruders.core;
import org.springframework.context.ApplicationContext;
import com.kruders.bean.Employee;
public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Beans.xml");
        Employee employee = (Employee) context.getBean("employee");
        System.out.println("Name " + employee.getName());
        System.out.println("Age " + employee.getAge());

When you run the above example you’ll get an output like:

Name Puneet
Age 22

The folder structure of the example is shown below in Figure 52.1

Figure 52.1 Figure 52.1

You can download the source code of this example here.

No comments yet.

Leave a Reply