Saturday, August 28, 2021

@Required Annotation in Spring Framework

In your Spring bean you may have some fields for which you want to ensure that those fields have been populated. Spring framework has a @Required annotation to ensure that.

@Required annotation in Spring

The @Required annotation applies to bean property setter methods. This annotation simply indicates that the bean property annotated with the @Required annotation must be configured to be dependency-injected with a value, through an explicit property value in a bean definition or through autowiring.

If the property annotated with @Required annotation is not set, BeanInitializationException exception will be thrown.

For Spring @Required annotation to work you also need to register RequiredAnnotationBeanPostProcessor that enforces required JavaBean properties to have been configured. Rather than directly registering RequiredAnnotationBeanPostProcessor preferred way is to include the <context:annotation-config/> tag in an XML-based Spring configuration. By using this tag following post-processors are implicitly registered AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor and RequiredAnnotationBeanPostProcessor.

You can also use <context:component-scan> if you are configuring your beans to be automatically discovered in Spring.

Example using Spring @Required annotation

In this example there are two classes Person.java and Employee.java. In Employee class there is an object of Person class and also a field designation. Setter methods for both are marked as @Required.

Employee.java

import org.springframework.beans.factory.annotation.Required;

public class Employee {
 
 private String designation;
 private Person person;

 public String getDesignation() {
  return designation;
 }
 @Required
 public void setDesignation(String designation) {
  this.designation = designation;
 }

 public Person getPerson() {
  return person;
 }
 @Required
 public void setPerson(Person person) {
  this.person = person;
 }
 
 public String toString(){
  return "Name - " + person.getName() + "Age - " + person.getAge();
  
 }
}

Person.java

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

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:annotation-config/>
    
    <bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
     
    </bean>
    
    <bean id="personBean" class="org.netjs.exp.Spring_Example.Person">
        <property name="name" value="Ram" />
        <property name="age" value="25" />
     </bean>
  
</beans>

Here notice the inclusion of <context:annotation-config/> tag. You also need to include context namespace for the same.

In the configuration values for the properties in employeeBean are not set. Since these fields are marked as @Required so you should get an exception.

You can run the code using the following Java class.

public class App {
    public static void main( String[] args ){
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
          ("appcontext.xml");
    }
}

As expected BeanInitializationException exception is thrown.

 Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeBean' defined in class path resource [appcontext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Properties 'designation' and 'person' are required for bean 'employeeBean'

Now let’s correct the configuration file and add the properties with value.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:annotation-config/>
    
    <bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
        <property name="person" ref="personBean" />
        <property name="designation" value="Manager" />
    </bean>
    
    <bean id="personBean" class="org.netjs.exp.Spring_Example.Person">
        <property name="name" value="Ram" />
        <property name="age" value="25" />
     </bean>
  
</beans>

Now if you run it using the following Java class.

public class App {
    public static void main( String[] args ){
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
         ("appcontext.xml");
     Employee emp = (Employee)context.getBean("employeeBean");
     System.out.println("Employee Name " + emp.getPerson().getName());
    }
}

Output

Employee Name Ram

That's all for this topic @Required Annotation in Spring Framework. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. @Resource Annotation in Spring Autowiring
  2. @Conditional Annotation in Spring
  3. Wiring Collections in Spring
  4. Circular Dependency in Spring Framework
  5. Spring Profiles With Examples

You may also like-

  1. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  2. Spring NamedParameterJdbcTemplate Select Query Example
  3. Inheritance in Java
  4. Type Casting in Java With Conversion Examples
  5. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  6. Nested class and Inner class in Java
  7. Java Stream API Tutorial
  8. Volatile Keyword in Java With Examples

No comments:

Post a Comment