spring—web.xml中配置spring监听器

在web.xml中添加:

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


猜你喜欢

转载自blog.csdn.net/cdw_sunshine/article/details/80378840