ApplicationContextaware works

白昼怎懂夜的黑 提交于 2019-12-06 02:57:08

You are confusing few things. First of all we are talking about ApplicationContextAware class, right? It has only one method:

setApplicationContext(ApplicationContext applicationContext)

Which you usually implement like this:

public class MyFancyBean implements ApplicationContextAware {

  private ApplicationContext applicationContext;

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

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

}

However you rarely need to access ApplicationContext directly. Typically you start it once and let beans populate themselves automatically.

I need to use the applicationContext.xml in my java class to use the spring beans in it.

Here you go:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

Note that you don't have to mention files already included in applicationContext.xml. Now you can simply fetch one bean by name or type:

ctx.getBean("someName")

Note that there are tons of ways to start Spring - using ContextLoaderListener, @Configuration class, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!