Reputation: 573
I trying to load an applicationContext.xml from java class in a web application using
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
and
ApplicationContext context = new FileSystemXmlApplicationContext("applicationContext.xml");
My question is how to load applicationContext.xml from a java class. The applicationContext.xml is WEB-INF. Is that possible?
Upvotes: 2
Views: 10211
Reputation: 280168
A ContextLoaderListener
is used when you want to load a specific context that will act as your context root. If you want to load additional contexts for whatever reason, you can define your own ServletContextListener
, create your ApplicationContext
instances, and put them in the ServletContext
attributes so that they are available to the web application
public class AdditionalContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sce) {
// destroy those contexts maybe
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ApplicationContext context = ...; // get your context
sce.getServletContext().setAttribute("someContextIdentifier", context);
}
}
Upvotes: 2
Reputation: 1209
You can use the ContextLoaderListener
in your web.xml
file:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Then you can use the WebApplicationContext
to load the context:
WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
Hope this helps.
Upvotes: 6