@Required Annotation in spring

The @Required annotation in Spring applies to bean property setter methods, as in the following example:

Tutorial Content: Spring tutorial for beginners

This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on.

Suppose you have very large application and you get   NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

2.Capital.java

This is also simple pojo class having one attribute called “capitalName”.

Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java

3.ApplicationContext.xml

Now you can note here that we have not injected capital property into country class but we have used it for getting capitalName in below RequiredAnnotationInSpringMain class.

4.RequiredAnnotationInSpringMain.java

This class contains main function.Create RequiredAnnotationInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into RequiredAnnotationInSpringMain.java

5.Run it:

When you will run above application,you will get following as output.
When you run it,you will get exception complaining “Property ‘capital’ is required for bean ‘CountryBean'”

That’s all about Required annotation in Spring.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *