1. 程式人生 > >Spring在web開發中的應用

Spring在web開發中的應用

ica ati spring 配置 還需要 erl 常量 tlist web.xml list

(1)在 web 項目中要使用 spring 需要導入一個 jar 包:
spring-web-4.2.4.jar包
(2)在 web.xml 文件中配置 Listener

1 <listener>
2     <listener-class>
3     org.springframework.web.context.ContextLoaderListener
4     </listener-class>
5 </listener>

這個 ContextLoaderListener 它實現了 ServletContextListener.在這個 listener 中,當服務器啟動時,將 ApplicationContext 對象,其實是它的一個實現類WebApplicationContext,對象存入到了 ServletContext 中。
(3)我們還需要在 web.xml 文件中配置 applicationContext.xml 文件的位置,默認情況下會在 WEB-INF 目錄 下查找 applicationContext.xml
如果 applicationContext.xml 文件不在默認位置,我們可以在 web.xml 文件中配置。

1 <context-param>
2     <param-name>contextConfigLocation</param-name>
3     <param-value>classpath:applicationContext.xml</param-value>
4 </context-param>

Classpath:applicationContext.xml 它代表的是在當前工程的類路徑下(可以理解成是在 src)下來查找 applicationContext.xml 文件。
contextConfigLocation 它是在 listener 中聲明的一個常量,描述的就是 spring 配置文件的位置。
經過上述配置後,在web開發中就可以使用spring框架了。

Spring在web開發中的應用