spring自注入如何与@Resource配合使用?

发布于 2024-11-08 16:34:05 字数 505 浏览 0 评论 0原文

这是一个了解spring内部的问题。由于 @Autowired 不起作用,因此建议在 Spring 中自行注入 Bean 的几种解决方法。这里有一些 线程。我想知道自注入在技术上与@Resource注释一起工作的原因以及如何工作?


@Service(value = "someService")
public class UserService implements Service{
   @Resource(name = "someService")
   private Service self;
}

任何到 spring 源代码的链接将不胜感激。谢谢。

This is a question to understand spring internals. There are a couple of workarounds suggested for self injection of a bean in spring because @Autowired doesn't work. Here are few threads. I would like to know the reason why and how does self injection work technically with @Resource annotation?


@Service(value = "someService")
public class UserService implements Service{
   @Resource(name = "someService")
   private Service self;
}

Any links to the spring source code would be appreciated. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嗳卜坏 2024-11-15 16:34:05

从另一个线程我得到了一个看起来相当不错的回复。基本上它指出 spring 专门添加了处理 @Autowired beans 的防御性检查,但 @Resource beans 绕过它,因此它可以工作。

From another thread I got a response which seems fairly ok. Basically it states that spring specially adds defensive checks for handling @Autowired beans but @Resource beans bypass it and hence it works.

粉红×色少女 2024-11-15 16:34:05

我不知道 spring 到底是如何处理它的,但这里有一些选项(例如 CDI 规范使用这些选项):

  • 不完整的实例。当bean被实例化并放入上下文中时,它们的状态被设置为“不完整”——也就是说,它们的实例存在,但它们的依赖项没有注入。因此,第一个 bean 被实例化,放入上下文中,并在下一阶段注入它们的依赖项。这使得上述情况变得微不足道 - 容器首先创建实例,然后对于每个注入点,从上下文本身获取所需的 bean,在本例中

  • 代理。为每个 bean 创建一个代理,以便它拥有 bean,而无需实际实例化这些 bean。它创建代理(通过接口/具体类),将它们相互注入,并在需要时传递代理。最后,每个代理都会获得其实际的 bean。上面的情况可能不是这样,因为 CDI 使用它来处理循环构造函数注入。

I don't know how exactly spring handles it, but here are a few options (the CDI specification uses these for example):

  • incomplete instances. When beans are instantiated and put in the context, their status is set as 'incomplete' - that is, their instance exists but their dependencies are not injected. Thus, first beans are instantiated, put in the context, and on the next stage their dependencies are injected. This makes the above case trivial - the container first create the instance and then, for each injection point, gets the desired bean from the context - itself, in this case

  • proxies. A proxy is created for each bean, so that it has beans without actually having instantiated the beans. It creates the proxies (by interface/concrete class), injects them into one another, and passes proxies around when needed. Finally each proxy gets its actual bean. This is perhaps not the case above, because this is used by CDI to handle circular constructor injection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文