Emilien Brigand
Emilien Brigand

Reputation: 11031

Exception thrown by @Autowired and @Required

I read that the @Required annotation throw this exception if the container can't find the bean for the dependency injection: org.springframework.beans.factory.BeanInitializationException

And for @Autowired the exception is: org.springframework.beans.factory.BeanCreationException

Considering those scenarios: I use @Required in a bean A to inject another bean B that does not exist, then I start the application. I use @Autowired in a bean A to inject another bean B that does not exist, then I start the application.

i would like to know when the exception for @Required and @Autowired are thrown? is it the same time? When the spring application context is loaded?

Upvotes: 1

Views: 1148

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52366

@Required annotation is being processed by Spring using RequiredAnnotationBeanPostProcessor and @Autowired by AutowiredAnnotationBeanPostProcessor. According to the source code here and here, respectively, these two post processors are ordered. The one for @Autowired has order of Integer.MAX_VALUE - 2 while the one for @Required is Integer.MAX_VALUE - 1. According to Spring's Ordered interface, the lower the value higher the priority.

Based on that, I believe @Autowired bean post processor will run before the one for @Required. So, to answer your question, a possible exception for @Autowired will be thrown before the one for @Required, when the spring application context is created.

Upvotes: 3

Related Questions