天天看點

Spring在javaweb工程中的簡單配置與應用

一、導入spring與web相關的jar包。這裡注意由于我之前起的web項目,然後是通過java的application做的哦實驗,是以所有的jar包都是導入在了src的library中。在運作web的時候會出現各種class找不到,是以還需要将jar包導入到/WebContent/WEB-INF/lib中。

二、在web.xml中添加如下關于spring的代碼:

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

這裡classpath:applicationContext-*.xml表示spring的配置檔案從src檔案下搜尋以applicationContext-*開頭的檔案。

三、servlet中如果需要spring提供的bean的話,如下使用:

ServletContext servletContext = this.getServletContext();       
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
       	UserDao userDao = (UserDao)ctx.getBean("mysqlDaoImpl");