Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 @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?

like image 776
Rachel Avatar asked Aug 22 '11 02:08

Rachel


People also ask

What is the use of @inject in Spring?

@Inject annotation is a standard annotation, which is defined in the standard "Dependency Injection for Java" (JSR-330). Spring (since the version 3.0) supports the generalized model of dependency injection which is defined in the standard JSR-330.

Which of the following is not a valid difference between @inject and @autowired annotation Mcq?

Which of the following is not a valid difference between @Inject and @Autowired annotations? There is no difference and both can be used interchangeably. @Inject annotation is part of Java EE 7's Context and Dependency Injection framework while @Autowired is the Spring Frameworks own implementation.

What is a difference between @autowired @resource and inject?

The only difference is that the @Autowired annotation is part of the Spring framework. This annotation has the same execution paths as the @Inject annotation, listed in order of precedence: Match by Type. Match by Qualifier.

What is the use of @inject annotation?

Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class. @Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.


1 Answers

Assuming here you're referring to the javax.inject.Inject annotation. @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 @Autowired annotation.

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.

like image 61
pap Avatar answered Oct 12 '22 20:10

pap