spring—web.xml中配置spring監聽器
阿新 • • 發佈:2018-12-13
<!-- spring容器生命週期監聽器配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 指定spring配置檔案位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
將建立容器的程式碼放入Action方法中,意味著每次執行Action方法都會建立一次容器.不可以這樣做! 要保證在web專案中只存在一個spring容器物件,解決方案: 方案1:使用靜態程式碼塊來建立spring容器.不建議.會導致與web應用相關的功能失效. 方案2:使用spring容器提供的解決方案. 提供一個ServletContextListener的實現類. 在實現類中,將容器建立以及銷燬與ServletContext物件的建立與銷燬繫結. 容器建立好之後,會放入application域中.
取出容器物件: spring提供了一個工具類.使用工具類中的方法從application域中取值
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> { private Customer customer = new Customer(); //列表查詢 //使用解耦servletAPI public String list() throws Exception { //1 獲得servletContext物件 ServletContext sc = ServletActionContext.getServletContext(); //2 呼叫工具方法從sc中獲得applicationContext容器 WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc); //3 從容器中獲得物件 CustomerService cs = (CustomerService) ac.getBean("customerService"); //================================================================================== //1 呼叫Service List<Customer> list = cs.findAll(); //2 放入request域 //ActionContext.getContext().put("list", list); ActionContext.getContext().getValueStack().push(list); //3 轉發到列表頁面 return "list"; } @Override public Customer getModel() { return customer; } }
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!-- 配置Dao物件 -->
<bean name="customerDao" class="cn.cdw.dao.impl.CustomerDaoImpl" ></bean>
<bean name="userDao" class="cn.cdw.dao.impl.UserDaoImpl" ></bean>
<!-- 配置Service物件 -->
<bean name="customerService" class="cn.cdw.service.impl.CustomerServiceImpl" >
<property name="cd" ref="customerDao" ></property>
</bean>
<bean name="userService" class="cn.cdw.service.impl.UserServiceImpl" >
<property name="ud" ref="userDao" ></property>
</bean>
</beans>