Spring框架
是一站式的轻量级的开源框架Spring
整合struts+Spring 其中Spring的作用是替代了传统的new的方式在action层和service层和dao层创建对象,将创建对象的工作交给了Spring容器去创建,并通过Set方法,注入
步骤,首先添加所需要的jar包,除了基本的Spring需要的4+2个jar包
两个日志包
4个基本包之外
还需要添加Spring-web-4.3.6-RELEAES..jar
首先在web.xml来书写这样一段代码以保证能够通过一个WebApplicationContext对象来获取javabean实例对象
<!-- 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层-service层把对象书写成成员属性,并封装Set方法
action 层
EmployeeService service ;//服务层的对象
// 3.声明服务层对象
private UserService us;
service层
//声明dao层的对象
EmployeeDAO dao ;
//声明dao层对象
UserDAO userDAO ;
再书写applicationContext.xml中配置相应的bean属性和类路径
<?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.3.xsd">
<!-- 注入dao -->
<bean name="empDAO" class="dao.jdbc.EmployeeDAOImpl"></bean>
<bean name="userDAO" class="dao.jdbc.UserDAOImpl"></bean>
<!-- 注入service -->
<bean name="employeeservice" class="service.EmployeeService">
<property name="dao" ref="empDAO"></property>
</bean>
<bean name="userservice" class="service.UserService">
<property name="userDAO" ref="userDAO"></property>
</bean>
</beans>
在Action通过获取webApplicationContext方式来创建相应的对象EmployeeService
ServletContext sc = ServletActionContext.getServletContext();
//2.拿到application对象
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
service = (EmployeeService) wac.getBean("employeeservice");
对象UserService
//1.拿到ServletContext对象
ServletContext sc = ServletActionContext.getServletContext();
//2.拿到application对象
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
us = (UserService) wac.getBean("userservice");