如何注入ApplicationContext本身
我想将 ApplicationContext
本身注入到一个 bean 中。
类似
public void setApplicationContext(ApplicationContect context) {
this.context = context;
}
春天可能吗?
I want to inject an ApplicationContext
itself to a bean.
Something like
public void setApplicationContext(ApplicationContect context) {
this.context = context;
}
Is that possible in spring?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
以前的评论都可以,但我通常更喜欢:
Previous comments are ok, but I usually prefer:
很简单,使用
ApplicationContextAware
接口。然后在您实际的 applicationContext 中您只需要引用您的 bean 即可。
Easy, using the
ApplicationContextAware
interface.Then in your actual applicationContext you only need to reference your bean.
是的,只需实现 ApplicationContextAware< /a> - 界面。
Yes, just implement the ApplicationContextAware -interface.
我在上面看到一些关于 @Autowired 仍然无法工作的评论。以下内容可能会有所帮助。
这是行不通的:
你必须这样做:
或这样:
另请注意,Upload 是必须在 @PostConstruct 范围内设置的另一个组件。这对我来说是一场噩梦。希望这有帮助!
我差点忘了提到 @Scope 注释对于您的 Bean 可能是必需的,如下所示。在 Bean 中使用 Upload 时就会出现这种情况,因为 UI 在创建 Bean 之前不会实例化/附加,并且会导致抛出空引用异常。使用 @Route 时不会这样做,但使用 @Component 时会这样做 - 所以后者不是一个选项,如果 @Route 不可行,那么我建议使用 @Configuration 类来创建具有原型范围的 bean。
I saw some comments above about @Autowired not working still. The following may help.
This will not work:
You must do this:
or this:
Also note that Upload is another component that must be set within the scope of @PostConstruct. This was a nightmare for me to figure out. Hope this helps!
I almost forgot to mention that the @Scope annotation may be necessary for your Bean, as seen below. This was the case when using Upload within a Bean because the UI is not instantiate/attached prior to the Bean being created and will cause a Null Reference Exception to be thrown. It won't do so when using @Route, but will when using @Component - so the latter is not an option and if @Route is not viable, then I would recommend using @Configuration class to create the bean with the prototype scope.
特殊解决方案:从任何(非 Spring)类获取 Spring beans
Special solution: get Spring beans from any (non Spring) classes