What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?
I am going through some blogs on SpringSource and in one of the blogs, author is using
@Inject and I suppose he can also use
Here is the piece of code:
@Inject private CustomerOrderService customerOrderService;
I am not sure about the difference between
@Autowired and would appreciate it if someone explained their difference and which one to use under what situation?
Assuming here you're referring to the
@Inject is part of the Java CDI (Contexts and Dependency Injection) standard introduced in Java EE 6 (JSR-299), read more. Spring has chosen to support using the
@Inject annotation synonymously with their own
So, to answer your question,
@Autowired is Spring's own annotation.
@Inject is part of a Java technology called CDI that defines a standard for dependency injection similar to Spring. In a Spring application, the two annotations works the same way as Spring has decided to support some JSR-299 annotations in addition to their own.
Read more... Read less...
Here is a blog post that compares
@Autowired, and appears to do a pretty comprehensive job.
From the link:
With the exception of test 2 & 7 the configuration and outcomes were identical. When I looked under the hood I determined that the ‘@Autowired’ and ‘@Inject’ annotation behave identically. Both of these annotations use the ‘AutowiredAnnotationBeanPostProcessor’ to inject dependencies. ‘@Autowired’ and ‘@Inject’ can be used interchangeable to inject Spring beans. However the ‘@Resource’ annotation uses the ‘CommonAnnotationBeanPostProcessor’ to inject dependencies. Even though they use different post processor classes they all behave nearly identically. Below is a summary of their execution paths.
Tests 2 and 7 that the author references are 'injection by field name' and 'an attempt at resolving a bean using a bad qualifier', respectively.
The Conclusion should give you all the information you need.
To handle the situation in which there is no wiring, beans are available with
required attribute set to
But when using
@Inject, the Provider interface works with the bean which means that the bean is not injected directly but with the Provider.
Better use @Inject all the time. Because it is java configuration approach(provided by sun) which makes our application agnostic to the framework. So if you spring also your classes will work.
If you use @Autowired it will works only with spring because @Autowired is spring provided annotation.