2011-06-23 31 views

回答

111

來自spring文檔

Spring可以很容易地集成到任何基於Java的web框架中。您只需要在您的web.xml中聲明ContextLoaderListener,並使用contextConfigLocation來設置要加載的上下文文件。

<context-param>

<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 ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext()); 
SomeBean someBean = (SomeBean) ctx.getBean("someBean"); 

更多信息參見http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html

+2

如何訪問上下文?並且你是否說應用程序一啓動,上下文就會加載Spring Context?請澄清一下,因爲我對Spring很陌生。感謝您的回覆 – tamilnad

+1

查看更新回答 – ddewaele

+0

以下是與WebApplicationContextUtils相關的最新API的鏈接。 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/context/support/WebApplicationContextUtils.html – Ajitesh

34

還可以指定上下文位置相對電流的類路徑,其可以是優選的

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath*:applicationContext*.xml</param-value> 
</context-param> 

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 
+0

'*'的意義是什麼?沒有它,它就無法工作:'IOException從ServletContext資源解析XML文檔[/>classpath:/applicationContext.xml];嵌套的異常是java.io.FileNotFoundException:無法打開ServletContext資源[/> classpath:/applicationContext.xml]' – DavidS

+1

我剛剛發現了一篇博客文章,回答關於'classpath *'[這裏](http:// www。 gridshore.nl/2008/05/13/spring-application-context-loading-tricks/)。 – DavidS

13

也可以在定義的servlet本身加載的上下文( WebApplicationContext

<servlet> 
    <servlet-name>admin</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value> 
       /WEB-INF/spring/*.xml 
      </param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
    <servlet-name>admin</servlet-name> 
    <url-pattern>/</url-pattern> 
    </servlet-mapping> 

而不是(的ApplicationContext

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

缺點是,它會加載上下文只爲與上述方法的上下文將被加載爲多個入口點這個特定彈簧的入口點(DispatcherServlet)(例如。Webservice Servlet, REST servlet等)

上下文通過ContextLoaderListener加載將事實上是專門爲DisplacherServlet加載的父上下文。因此,基本上可以在應用程序上下文中加載所有業務服務,數據訪問或存儲庫bean,並分離出控制器,並將解析器bean查看到WebApplicationContext。

相關問題