2013-10-10 36 views
1

我試圖加載從Java類中的applicationContext.xml使用如何加載applicationContext.xml的

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

ApplicationContext context = new FileSystemXmlApplicationContext("applicationContext.xml"); 

Web應用程序我的問題是如何從加載applicationContext.xml中一個java類。 applicationContext.xml是WEB-INF。那可能嗎?

回答

6

您可以在web.xml文件中使用ContextLoaderListener

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

然後你可以使用WebApplicationContext加載上下文:

WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext()); 

希望這有助於。

+0

@Sufala AS是這樣的有用嗎? –

+0

謝謝,我明白了!請參閱:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-java-instantiating-container-web – Eddy

2

A ContextLoaderListener用於加載將充當上下文根的特定上下文。如果要加載額外的上下文是什麼原因,你可以定義自己的ServletContextListener,創建ApplicationContext實例,並把它們放在ServletContext屬性,使它們可用於網絡應用程序

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); 
    } 

} 
相關問題