@Inject 和 @Autowired 有什么区别
我只是想知道 @Inject 和 @Inject 之间有什么区别? @Autowired 何时使用每一个?或者它们正在做同样的事情?
如果我有一个具有范围的 spring bean:
@Service
@Scope("singleton")
我可以为它进行依赖注入吗?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,他们也这样做。 @Inject是来自javax.inject的注解,它只是依赖注入的API。在 Spring 中,您可以同时使用两者,因为我认为 Spring 提供了 @Inject 的实现,它与 Spring 环境中的 @Autowired 执行相同的操作。
Matthias Wessendorf 在博客中介绍了这一点:http:// matthiaswessendorf.wordpress.com/2010/04/20/spring-3-0-and-jsr-330-part-2/
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?
我认为值得指出的是,如果您使用@Autowired,您正在创建对Spring的依赖关系,其中使用@Inject,您将能够换出另一个支持
JSR 330
的依赖注入框架。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 supportsJSR 330
.第一,@Autowired是由Spring Framework定义的,但@Inject来自“Java依赖注入”(JSR-330)”
第二,@Inject不接受必需的属性因此,如果它找不到任何 bean,它将失败并出现错误,但 @Autowired 可以带有 required=false 并允许可以为空的字段,
@Inject 注释的优点是而不是注入。一个直接引用,您可以要求 @Inject 注入 Provider 接口,除其他外,还可以实现 bean 引用的延迟注入和 bean 的多个实例的注入。
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.