@Required
We use the @Required annotation to tell Spring that a property on a bean is required.
Student.java
Here we have applied the @Required annotation to the method setStudentId.
package com.skills421.examples.spring.model;
import org.springframework.beans.factory.annotation.Required;
public class Student
{
private String name;
private String email;
private String studentId;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getStudentId()
{
return studentId;
}
@Required
public void setStudentId(String studentId)
{
this.studentId = studentId;
}
public String toString()
{
StringBuilder sb = new StringBuilder("Student[");
sb.append("name="+name);
sb.append(", email="+email);
sb.append(", studentId="+studentId);
sb.append("]");
return sb.toString();
}
}
student1.xml
This will do nothing if we do not add the RequiredAnnotationBeanPostProcessor bean to our Spring config xml file.
<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.xsd"> <!-- Person Beans --> <bean id="jondoe" class="com.skills421.examples.spring.model.Student"> <property name="name" value="Jon Doe" /> <property name="email" value="jon.doe@gmail.com" /> <property name="studentId" value="DoeJ-001" /> </bean> <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" /> </beans>
TestStudent1.java
Now we can bring it all together in our Test Suite.
package com.skills421.example.spring;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.skills421.examples.spring.model.Student;
public class TestStudent1
{
private static AbstractApplicationContext context;
@BeforeClass
public static void setupAppContext()
{
context = new ClassPathXmlApplicationContext("student1.xml");
}
@AfterClass
public static void closeAppContext()
{
if(context!=null)
{
context.close();
}
}
@After
public void printBlankLine()
{
System.out.println();
}
@Test
public void test1()
{
System.out.println("jondoe");
Student person = context.getBean("jondoe",Student.class);
System.out.println(person);
}
}


Leave a comment