ApplicationContextaware works

那年仲夏 提交于 2019-12-07 12:19:43

问题


I need to know how applicatoncontextaware works. I have applicationContext.xml which has some import resource(another applicationContext). I need to use the applicationContext.xml in my java class to use the spring beans in it.

I came to know the applicationcontextaware class which is used to get the spring beans inside java class.Applicationaware has the set and getapplicationcontext() methods. getapplicationcontext() is defined as static.

How do the applicationcontextware loads the applicationContext.xml? whether do i need to give the location of applicationContext.xml so that applicationcontextaware loads? How can i use it in my java class?


回答1:


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.



来源:https://stackoverflow.com/questions/10128467/applicationcontextaware-works

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