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?
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