Spring @Required Annotation Example
Spring framework provides a method-level annotation which is applied to the bean property setter methods for making the setter-injection mandatory. This tutorial will explore the Spring-specific @Required
annotation.
1. Introduction
1.1 Spring Framework
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows the developer to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
1.2 Spring @Required Annotation
The @Required
annotation in spring is a method-level annotation applied to the setter method of a bean property and thus making the setter-injection mandatory. This annotation indicates that the required bean property must be injected with a value at the configuration time. Below snippet shows how to use this annotation.
Code Snippet
import org.springframework.beans.factory.annotation.Required; public class Company { private Integer cid; private String cname; @Required public void setCid(Integer cid) { this.cid = cid; } public Integer getCid() { return cid; } ..... }
1.2.1 Activate @Required annotation
To activate this annotation in spring, developers will have to include the <context:annotation-config />
tag in the configuration file. Below snippet shows how to include this tag in the configuration file:
Code Snippet
<beans //... xmlns:context="http://www.springframework.org/schema/context" //... xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- To activate the @Required annotation in spring --> <context:annotation-config /> </beans>
In addition, the same can also be achieved by specifying the bean definition of the RequiredAnnotationBeanPostProcessor
class in the configuration file. Below snippet shows how to include the object of this class in the configuration file:
Code Snippet
<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"> <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> </beans>
Now, open up the Eclipse IDE and let us see how to implement this annotation in the spring framework!
2. Spring @Required Annotation Example
Here is a systematic guide for implementing this tutorial in the spring framework.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8, MySQL and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring</groupId> <artifactId>SpringRequiredAnnotation</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> </project>
We can start adding the dependencies that developers want like Spring Core, Spring Context etc. Let us start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependencies for the spring framework. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring</groupId> <artifactId>SpringRequiredAnnotation</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.6.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.6.RELEASE</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.2 Java Class Creation
Let us write the Java classes involved in this application.
3.2.1 Implementation of Employee Model
This POJO class contains three setter methods for demonstrating the use of @Required
annotation. Add the following code to it:
Employee.java
package com.spring.pojo; import org.springframework.beans.factory.annotation.Required; public class Employee { private String name; private String designation; private String company; @Required public void setName(String name) { this.name = name; } public String getName() { return name; } @Required public void setDesignation(String designation) { this.designation = designation; } public String getDesignation() { return designation; } public void setCompany(String company) { this.company = company; } public String getCompany() { return company; } @Override public String toString() { return "Employee [name=" + name + ", designation=" + designation + ", company=" + company + "]"; } }
3.2.2 Implementation of Utility Class
The implementation class will get the bean definition from the context file and demonstrate the use of @Required
annotation in the spring framework. Add the following code to it:
AppMain.java
package com.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.pojo.Employee; public class AppMain { @SuppressWarnings("resource") public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("required-annotation.xml"); Employee emp = ac.getBean("myemployee", Employee.class); System.out.println(emp.toString()); } }
3.3 Configuration Files
Let us write all the configuration files involved in this application.
3.3.1 Required
A typical bean configuration file for understanding the @Required
annotation will look like this:
required-annotation.xml
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Used to activate the @Required annotation in Spring --> <context:annotation-config /> <bean id="myemployee" class="com.spring.pojo.Employee"> <!-- Required property --> <property name="name" value="Charlotte O' Neil" /> <!-- Required property --> <property name="designation" value="Technical Leader" /> <property name="company" value="Test Ltd." /> </bean> </beans>
4. Run the Application
To execute the application, right click on the AppMain
class, Run As -> Java Application
. Users can debug the example and see what happens after every step. Enjoy!
5. Project Demo
When users will run this tutorial, they will get the following logs as output.
Output Logs
Sep 09, 2018 1:19:23 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@45283ce2: startup date [Sun Sep 09 13:19:23 IST 2018]; root of context hierarchy Sep 09, 2018 1:19:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [required-annotation.xml] Employee [name=Charlotte O' Neil, designation=Technical Leader, company=Test Ltd.]
In case any bean property with the @Required
annotation has not been set, a BeanInitializationException
will be thrown by this bean processor.
Error Logs
Sep 09, 2018 1:25:29 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@45283ce2: startup date [Sun Sep 09 13:25:29 IST 2018]; root of context hierarchy Sep 09, 2018 1:25:29 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [required-property-missing.xml] Sep 09, 2018 1:25:29 PM org.springframework.context.support.AbstractApplicationContext refresh WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myemployee' defined in class path resource [required-property-missing.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'designation' is required for bean 'myemployee' Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myemployee' defined in class path resource [required-property-missing.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'designation' is required for bean 'myemployee' at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:587) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:144) at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:85) at com.spring.AppMain.main(AppMain.java:12) Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'designation' is required for bean 'myemployee' at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:156) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1348) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:578) ... 11 more
That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
6. Conclusion
This post defines the @Required
annotation in the spring framework and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of spring @Required
annotation for beginners.
You can download the full source code of this example here: SpringRequiredAnnotation