Spring @Required annotation example

The Spring @Required annotation example shows you how to use the @Required annotation. This annotation helps you check some dependency at startup rather than at runtime. So that this make it more clear and quicker to detech exceptions and errors. By default, this annotation is not configured, thus we must instruct the spring container explicitly.

Let’s see the detail example below.

Application Data Access Object(DAO)

We are creating simple HelloDAO class like below:

Application Service and Using Spring @Required Annotation Example

We are creating simple service class. This class has a property called HelloDAO which we annotated the setter method with @Required, like below:

Configuring Spring annotation
By default, the @Required annotation will not found by Spring. We have to configure the RequiredAnnotationBeanPostProcessor that check if all the bean properties with the @Required annotation have been configured correctly. We have three options to enable this RequiredAnnotationBeanPostProcessor:

a. Configure the bean directly by including a bean with class org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor in bean configuration file.
b. By adding the element in bean configuration file.
c. By adding the element in bean configuration file.

The below configuration uses element

Notice: if you want to disable or skip @Required Dependency Checking for class we can configure the bean definition with the org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.skipRequiredCheck and assign a value of true. This will skip the required annotation completely for that class, such as below:

Demo Spring application
In this Spring @Required annotation example, we create main class and load all the bean definitions using the constructor of the ApplicationContext. The Spring container will search required annoation and check its required dependencies at starting the application. If there are bean definitions that are missing required properties, the application will throw BeanInitializationException at startup.

Run the main above, the console will print BeanInitializationException like this

That’s it on the Spring @Required annotation example.

References
@Required Annotation Spring Doc
RequiredAnnotationBeanPostProcessor.java

Download complete source code, click link below

spring-@required-annotation-example.zip (10 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons