ApplicationContextaware有效

Jes*_*sie 3 spring applicationcontext

我需要知道applicatoncontextaware是如何工作的.我有applicationContext.xml,它有一些导入资源(另一个applicationContext).我需要在我的java类中使用applicationContext.xml来使用spring bean.

我开始了解applicationcontextaware类,它用于获取java类中的spring bean .Applicationaware具有set和getapplicationcontext()方法.getapplicationcontext()定义为static.

applicationcontextware如何加载applicationContext.xml?我是否需要提供applicationContext.xml的位置以便applicationcontextaware加载?我如何在我的java类中使用它?

Tom*_*icz 15

你很困惑.首先我们在谈论ApplicationContextAware课程,对吧?它只有一种方法:

setApplicationContext(ApplicationContext applicationContext)
Run Code Online (Sandbox Code Playgroud)

你通常这样实现:

public class MyFancyBean implements ApplicationContextAware {

  private ApplicationContext applicationContext;

  void setApplicationContext(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }

  public void businessMethod() {
    //use applicationContext somehow
  }

}
Run Code Online (Sandbox Code Playgroud)

但是,您很少需要ApplicationContext直接访问.通常,您启动一​​次,让bean自动填充.

我需要在我的java类中使用applicationContext.xml来使用spring bean.

干得好:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Run Code Online (Sandbox Code Playgroud)

请注意,您不必提及已包含的文件applicationContext.xml.现在您只需按名称或类型获取一个bean:

ctx.getBean("someName")
Run Code Online (Sandbox Code Playgroud)

请注意,有很多方法可以启动Spring - 使用ContextLoaderListener,@Configuration类等.

  • 如果Spring不直接控制整个应用程序,您可能需要它,例如,如果您从应用程序服务器实例中运行Spring,但是您希望将两者中的实例绑定在一起.从ApplicationContextAware javadoc中,它们列出了许多其他可能性,但也为您提供了首选替代方案,即除非您绝对不能使用XML/Annotations配置,否则您不应直接从上下文中获取. (2认同)