i am just wondering what is the difference between @Inject & @Autowired when to use each one ?, or they are doing the same thing ?
and if i have a spring bean which have a scope:
@Service
@Scope("singleton")
can i make dependency injection for it with both with no problems ?
thanks in advance.
@Inject and @Autowired both annotations are used for autowiring in your application. @Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application. Sr.
@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.
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.
Dependency Injection is a fundamental aspect of the Spring framework, through which the Spring container “injects” objects into other objects or “dependencies”. Simply put, this allows for loose coupling of components and moves the responsibility of managing components onto the container.
From what I know, they do the same. @Inject is an annotation from javax.inject, which is only the API for dependency injection. In Spring you can use both, as I think Spring provides an implementation for @Inject which does the same thing as @Autowired in Spring environments.
Matthias Wessendorf blogged about this here: http://matthiaswessendorf.wordpress.com/2010/04/20/spring-3-0-and-jsr-330-part-2/
How about reading the documentation?
JSR 330's @Inject annotation can be used in place of Spring's @Autowired in the examples below. @Inject does not have a required property unlike Spring's @Autowired annotation which has a required property to indicate if the value being injected is optional. This behavior is enabled automatically if you have the JSR 330 JAR on the classpath.
I think it is worth pointing out that, if you use @Autowired
, you are creating a dependency on Spring, where using @Inject
, you will be able to swap out another dependency injection framework that supports JSR 330
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With