开发者

What is the difference between @Inject and @Autowired

i am just wondering what is the dif开发者_开发知识库ference 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.


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.


First, @Autowired is defined by Spring Framework but @Inject came from "Dependency Injection for Java" (JSR-330)"

Second, @Inject doesn't take required attribute so if it fails to find any bean, it will fail with an error but @Autowired can come with required=false and will allow a nullable field.

Third, Advantage of @Inject annotation is that rather than inject a reference directly, you could ask @Inject to inject a Provider. The Provider interface enables, among other things, lazy injection of bean references and injection of multiple instances of a bean.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜