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 @Autowired
.
Here is the piece of code:
@Inject private CustomerOrderService customerOrderService;
I am not sure about the difference between @Inject
and @Autowired
and would appreciate it if someone explained their difference and which one to use under what situation?
As of Spring 3.0, Spring offers support for JSR-330 dependency injection annotations (
@Inject
,@Named
,@Singleton
).There is a separate section in the Spring documentation about them, including comparisons to their Spring equivalents.
In addition to the above:
prototype
.The
@Inject
annotation is one of the JSR-330 annotations collection. This has Match by Type,Match by Qualifier, Match by Name execution paths. These execution paths are valid for both setter and field injection.The behavior of@Autowired
annotation is same as the@Inject
annotation. The only difference is the@Autowired
annotation is a part of the Spring framework.@Autowired
annotation also has the above execution paths. So I recommend the@Autowired
for your answer.The key difference(noticed when reading the Spring Docs) between
@Autowired
and@Inject
is that,@Autowired
has the 'required' attribute while the @Inject has no 'required' attribute.Here is a blog post that compares
@Resource
,@Inject
, and@Autowired
, and appears to do a pretty comprehensive job.From the link:
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
@Autowired
required
attribute set tofalse
.But when using
@Inject
, the Provider interface works with the bean which means that the bean is not injected directly but with the Provider.