[英]What is the difference between @Inject and @Autowired
i am just wondering what is the difference between @Inject & @Autowired when to use each one ?, or they are doing the same thing ? 我只是想知道@Inject和@Autowired什么时候使用每个之间有什么区别?或者它们正在做相同的事情?
and if i have a spring bean which have a scope: 如果我有一个有范围的spring bean:
@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.
@Inject是javax.inject的注释,它只是依赖项注入的API。 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.
在Spring中,您可以同时使用两者,因为我认为Spring为@Inject提供了一个实现,该实现与Spring环境中的@Autowired相同。
Matthias Wessendorf blogged about this here: http://matthiaswessendorf.wordpress.com/2010/04/20/spring-3-0-and-jsr-330-part-2/ Matthias Wessendorf在这里发布了有关此内容的文章: 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.
在下面的示例中,可以使用JSR 330的@Inject注释代替Spring的@Autowired。 @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.
与Spring的@Autowired批注不同,@Inject没有必需属性,Spring的@Autowired注释具有必需属性,用于指示要注入的值是否可选。 This behavior is enabled automatically if you have the JSR 330 JAR on the classpath.
如果您在类路径上具有JSR 330 JAR,则会自动启用此行为。
我认为值得指出的是,如果使用@Autowired
,则将在Spring上创建依赖项,而使用@Inject
,则可以换出另一个支持JSR 330
依赖项注入框架。
First , @Autowired is defined by Spring Framework but @Inject came from "Dependency Injection for Java" (JSR-330)" 首先 ,@Autowired由Spring Framework定义,但是@Inject来自“ 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. 其次 ,@Inject不采用required属性,因此,如果找不到任何bean,它将失败并显示错误,但是@Autowired可以带有required = false并允许可为空的字段。
Third , Advantage of @Inject annotation is that rather than inject a reference directly, you could ask @Inject to inject a Provider. 第三 ,@Inject批注的优点是您可以要求@Inject注入提供程序,而不是直接注入引用。 The Provider interface enables, among other things, lazy injection of bean references and injection of multiple instances of a bean.
Provider接口可以实现Bean引用的延迟注入和Bean的多个实例的注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.