This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Question: What is the difference between @inject and @autowired in Spring? Under what conditions are they used?
I’m looking at some blogs on SpringSource, and in one of the other blogs, the author uses @inject, but I think he uses @AutoWired as well
Here is part of the code:
@Inject private CustomerOrderService customerOrderService;
Copy the code
I’m not sure what the difference is between @inject and @autowired, can someone explain the difference and usage scenario between the two?
Answer a
Suppose you say javax.inject.Inject annotation. Inject @Inject is part of Java CDI (Context and Dependency Injection), introduced in Java EE 6 (JSR-299). Spring has decided to support the use of the @Inject annotation with the same meaning as their @Autowired annotation
So, the answer to your question is that @Autowired is Spring’s own annotation. Inject is part of a Java technology called CDI that defines a spring-like dependency injection standard. In a Spring application, these two annotations are the same, because Spring has decided to support some jSR-299 annotations in addition to their own
Answer two
Here’s a blog that compares @Resource, @Inject, and @AutoWired, and it’s done pretty well
From that blog:
Except for Tests 2 and 7, the configuration and output are the same. When I looked under hood, I determined that the annotation ‘@autowired’ and ‘@Inject’ had the same effect. The two annotations AutowiredAnnotationBeanPostProcessor to inject dependencies. ‘@autowired’ and ‘@Inject’ can be used interchangeably to Inject beans. But the ‘@’ Resource ‘annotations using’ CommonAnnotationBeanPostProcessor to inject dependency. Although they use different processor classes, the effect is almost the same. Below is a summary of their execution paths.
The author refers to tests 2 and 7 as “injection by field name” and “an attempt to parse the bean using an error qualifier,” respectively.
The results here answer all your questions
The article translated from Stack Overflow:stackoverflow.com/questions/7…