如何注入ApplicationContext本身

mib*_*tec 60 java spring applicationcontext

我想把自己注入ApplicationContext一个bean.

就像是

public void setApplicationContext(ApplicationContect context) {
  this.context = context;
}
Run Code Online (Sandbox Code Playgroud)

那可能在春天吗?

sin*_*pop 117

以前的评论都可以,但我通常更喜欢:

@Autowired private ApplicationContext applicationContext;
Run Code Online (Sandbox Code Playgroud)

  • @Bariscan:我认为没有利弊.但是我更喜欢这个,因为@Autowired是我用来注入所有属性的东西,所以不同的做法只是beacuse是一个ApplicationContext? (9认同)
  • 虽然我同意`@Autowired`很好; 当涉及循环引用时,使用`@Autowired`和ApplicationContextAware之间的区别可能是惊人的.事实证明,简单地删除`@Autowired`解决了我在[循环依赖在春天]中描述的问题(http://stackoverflow.com/questions/3485347/circular-dependency-in-spring/17111644#17111644) (4认同)
  • +1顺便说一句,您是否了解直接@Autowired注入applicationContext或实现ApplicationContextAware接口之间的优缺点?谢谢. (3认同)

Joh*_*erg 38

使用ApplicationContextAware界面很简单.

public class A implements ApplicationContextAware {
  private ApplicationContext context;

  public void setApplicationContext(ApplicationContext context) {
      this.context = context;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的实际applicationContext中,您只需要引用您的bean.

<bean id="a" class="com.company.A" />
Run Code Online (Sandbox Code Playgroud)


esa*_*saj 12

是的,只需实现ApplicationContextAware -interface.