总结目录
一、什么是spring?
1.1 spring概述
Spring框架是一个开放源代码的J2EE应用程序框架,由Rod Johnson发起,是针对bean的生命周期进行管理的轻量级容器(lightweight container)。 Spring解决了开发者在J2EE开发中遇到的许多常见的问题,提供了功能强大IOC、AOP及Web MVC等功能。Spring可以单独应用于构筑应用程序,也可以和Struts、Webwork、Tapestry等众多Web框架组合使用,并且可以与 Swing等桌面应用程序AP组合。因此, Spring不仅仅能应用于JEE应用程序之中,也可以应用于桌面应用程序以及小应用程序之中。Spring框架主要由七部分组成,分别是 Spring Core、 Spring AOP、 Spring ORM、 Spring DAO、Spring Context、 Spring Web和 Spring Web MVC。
百度百科:https://baike.baidu.com/item/spring/85061
总结百度百科所述,spring框架就是用于J2EE开发的一站式框架,对EE开发的每一层都有解决方案,同时提供了强大的IOC以及AOP等扩展方式。
1.2 spring的优点
1.方便解耦,简化开发
2.AOP编程的支持
3.声明式事务的支持
4.方便程序的测试
5.方便集成各种优秀框架
6.降低Java EE API的使用难度
7.Java 源码是经典学习范例
1.3 spring框架结构
1.3.1 spring核心容器(Core Container)
其核心容器由spring-core, spring-beans, spring-context, springcontext-support,spring-expression 模块组成。
-
spring-core、spring-beans:提供了框架的基本部分,包括IOC和DI特性。
-
spring-context:在core和bean模块的基础上,添加了国际化(比如,使用资源束)、事件传播、资源加载和透明地创建上下文(比如,通过Servelet容器)等功能。
-
spring-expression:在运行时查询和操作对象图提供强大的表达式语言。
1.3.2 数据访问和集成(Data Access/Integration)
数据访问/集成层由JDBC、ORM、OXM、JMS和事务模块组成。
-
spring-JDBC:提供了一个jdbc抽象层,消除了繁琐的工作。
-
Transtions:支持对类进行程序化和声明式事务管理。
-
ORM:为流行的对象关系映射api提供集成层。
-
OXM:提供了一个支持对象/XML映射的抽象层。
-
JMS:(Java消息传递服务)包含用于生产和消费的功能。
1.3.3 Web
Web层由spring-web、spring-webmvc、spring-websocket和springwebmvc-portlet模块组成。
-
spring-web:提供了基本的面向web的集成特性。
-
spring -webmvc:也称为Web- servlet模块)包含Spring的modelview-controller (MVC)和Web应用程序的REST Web服务实现。
-
spring-webmvc-portlet:模块提供了用于Portlet环境的MVC实现,并反映了spring-webmvc模块的功能。
1.3.4 其他
还有其他一些重要的模块,像 AOP,Aspects,Instrumentation,Web 和测试模块。
-
AOP 模块提供了面向方面的编程实现,允许你定义方法拦截器和切入点对代码进行干净地解耦,从而使实现功能的代码彻底的解耦出来。使用源码级的元数据,可以用类似于.Net属性的方式合并行为信息到代码中。
-
Aspects 模块提供了与 AspectJ 的集成,这是一个功能强大且成熟的面向切面编程(AOP)框架。
-
Instrumentation 模块在一定的应用服务器中提供了类 instrumentation 的支持和类加载器的实现。
-
Messaging 模块为 STOMP 提供了支持作为在应用程序中 WebSocket 子协议的使用。它也支持一个注解编程模型,它是为了选路和处理来自 WebSocket 客户端的 STOMP 信息。
-
测试模块支持对具有 JUnit 或 TestNG 框架的 Spring 组件的测试。
二、spring入门
2.1 创建Web项目并引入Jar包
2.2.1 创建Web项目(略)
2.2.2 引入jar包
在 spring-framework-4.2.4.RELEASE\libs
的目录下有很多jar包,但是一般不需要全部引入,只引入必须的即可,也就是引入其核心jar包,即beans、context、core、expression包。以及必要的日志jar包。
2.2 编写测试类
2.2.1 编写用户类
public class User {
private String username;
private String password;
private Date birthday;
private List<String> hobby;
private Map<String,UserDao> likeUser;
/****get/set方法以及toString方法****/
}
2.2.2 编写dao类
- dao接口
public interface UserDao {
public void save();
}
- 普通dao
public class UserDaoimpl implements UserDao{
@Override
public void save() {
System.out.println("UserDaoimpl");
}
}
- hibernate dao
public class UserDaoHibernate implements UserDao {
@Override
public void save() {
System.out.println("UserDaoHibernate");
}
}
2.3 编写配置文件
2.3.1 创建 配置文件
在src的目录下创建 applicationContext.xml
配置文件。
2.3.1 引入约束
在 spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html
目录下的xsd-schema.html文件的最下边的约束引入。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.itheima.dao.impl.UserDaoHibernate"/>
2.3.3 编写配置
<bean id="userDao" class="com.itheima.dao.impl.UserDaoHibernate"/>
<bean name="birthday" class="java.util.Date"></bean>
<bean name="user" class="com.itheima.user.User">
<property name="username" value="张三"/>
<property name="password" value="zhangsan"/>
<property name="birthday" ref="birthday"/>
<property name="hobby">
<list>
<value>打篮球</value>
<value>玩电脑</value>
<value>玩游戏</value>
</list>
</property>
<property name="likeUser">
<map>
<entry key="lisi" value-ref="userDao"></entry>
</map>
</property>
</bean>
2.4 运行测试
2.4.1编写测试类并运行测试
public class SpringTest {
@Test
public void SpringDemo1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appliacationContext.xml");
UserDao bean = (UserDao) applicationContext.getBean("userDao");
bean.save();
}
@Test
public void SpringDemo2() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appliacationContext.xml");
User user = (User) applicationContext.getBean("user");
System.out.println(user);
}
}
2.5 入门总结
在以上入门案例中可以看出,在有两个实现类的情况下,如果要修改其实现类,在用原生的方法的情况下, 必须修改源码,这样就违背了OCP(Open Close Principle)原则,而使用spring,只需要去修改配置文件,极大的简化了开发,也遵循了OCP(Open Close Principle)原则。
而spring是如何根据配置文件来创建对象的呢?
三、Spring IOC与DI
3.1 IOC容器
3.1.1 什么是IOC容器?
IOC(控制反转)即控制权的转移,将我们创建对象的方式反转了,以前对象的创建是由我们开发人员自己维护,包括依赖关系也是自己注入。使用了spring之后,对象的创建以及依赖关系可以由spring完成创建以及注入,反转控制就是反转了对象的创建方式,从我们自己创建反转给了spring创建。
3.1.2 spring提供的工厂类
spring的工厂类主要是用于创建IOC容器,然后通过容器调用相应的方法,实现相应的功能。下图为Sppring工厂类的关系图:
-
BeanFactory工厂类:
-
这是一个最简单的容器,它主要的功能是为依赖注入 (DI) 提供支持。
-
他在调用getBean()的时候才会生成类的实例。
-
使用方法:
- 在上文入门程序中的加载配置文件方法,可以改成如下代码:
@Test public void SpringDemo1() { XmlBeanFactory applicationContext = new XmlBeanFactory (new ClassPathResource("appliacationContext.xml")); UserDao bean = (UserDao) applicationContext.getBean("userDao"); bean.save(); }
-
-
ApplicationContext工厂类:
- 它继承了BeanFactory类,被称为Spring的上下文。
- 它是在加载配置文件的时候就已经对配置文件中所有的类进行了了实例化。
- 两个常用子类:
- FileSystemXmlApplicationContext:从磁盘目录获取配置文件
- ClassPathXmlApplicationContext:从项目目录获取配置文件
- 使用方法:即入门程序中所使用的的方法。
3.1.3 spring的配置
3.1.3.1 Bean的相关配置:
-
bean标签的id与name属性
- id:使用了约束中的唯一约束。里面不能出现特殊字符的。
- name :没有使用约束中的唯一约束(理论上可以出现重复的,但是实际开发不能出现的)。里面可以出现特殊字符。l id :使用了约束中的唯一约束。里面不能出现特殊字符的。
-
bean标签的class属性
- 要实例化的类路径
-
bean标签的生命周期
- init-method:Bean被初始化的时候执行的方法。
- destroy-method:Bean被销毁的时候执行的方法(Bean是单例创建,工厂关闭)
-
bean标签的作用范围:
- scope:Bean的作用范围:
- singleton:默认的,Spring会采用单例模式创建这个对象。
- prototype:多例模式。。
- request:应用在web项目中,Spring创建这个类以后,将这个类存入到request范围中。
- session:应用在web项目中,Spring创建这个类以后,将这个类存入到session范围中
- globalsession:应用在web项目中,必须在porlet环境下使用。但是如果没有这种环境,相对于session。
- scope:Bean的作用范围:
3.2 DI
3.2.1 什么是DI?
DI—Dependency Injection,即“依赖注入”:组件之间依赖关系由容器在运行期决定,形象的说,即由容器动态的将某个依赖关系注入到组件之中。简单来说,就是在设置类的属性的时候,不用自己去手动设置,而是由Spring进行动态的注入。
3.2.3 spring的依赖注入
为了简单理解依赖注入,以下方法均为对入门案例中User类的属性注入。
3.2.3.1 构造方法注入
<bean name="user" class="com.itheima.user.User">
<constructor-arg name="username" value="李四"></constructor-arg>
<constructor-arg name="password" value="lisi"></constructor-arg>
<constructor-arg name="birthday" ref="birthday"></constructor-arg>
<constructor-arg name="hobby">
<list>
<value>打篮球</value>
<value>玩电脑</value>
<value>玩游戏</value>
</list>
</constructor-arg>
<constructor-arg name="likeUser">
<map>
<entry key="lisi" value-ref="userDao"></entry>
</map>
</constructor-arg>
</bean>
3.2.3.2 set方法注入
<bean name="user" class="com.itheima.user.User">
<property name="username" value="张三"/>
<property name="password" value="zhangsan"/>
<property name="birthday" ref="birthday"/>
<property name="hobby">
<list>
<value>打篮球</value>
<value>玩电脑</value>
<value>玩游戏</value>
</list>
</property>
<property name="likeUser">
<map>
<entry key="zhangsan" value-ref="userDao"></entry>
</map>
</property>
</bean>
3.2.3.3 P名称空间注入
<bean name="user3" class="com.itheima.user.User" p:username="王五" p:password="wangwu" p:birthday-ref="birthday" />
3.2.3.4 SpEL注入
spring3.0创建了一种新的方式用来配置对象的注入(Set或者构造参数),即为SpEL;它使用#{}来作为定界符,所有在大括号里的字符都将被认为是SpEL。
<bean name="user4" class="com.itheima.user.User">
<property name="username" value="#{'赵六'}"/>
<property name="password" value="#{'zhaoliu'}"/>
<property name="birthday" ref="#{birthday}"/>
</bean>
3.3 注解开发
3.3.1 引入Jar包
在注解开发中,除了要引入之前所说的六个包外,还要引入注解开发的 spring-aop-4.2.4.RELEASE.jar
包。
3.3.2 使用注解开发实现入门案例
3.3.2.1 修改配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- 引入context约束 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置扫描 -->
<context:component-scan base-package="com.itheima"/>
</beans>
3.3.2.2 修改测试类文件
- dao类
@Repository("hibernateUserDao")
public class UserDaoHibernate implements UserDao {
@Override
public void save() {
System.out.println("UserDaoHibernate");
}
}
@Repository("basicUserDao")
public class UserDaoimpl implements UserDao{
@Override
public void save() {
System.out.println("UserDaoimpl");
}
}
3.2.2.3 运行测试
- 测试类
注意:如果有set方法,注解应该加在set的方法上,如果没有set方法,注解添加到属性上
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class SpringTest02 {
@Resource(name="basicUserDao")
private UserDao basicUserDao;
@Resource(name="hibernateUserDao")
private UserDao hibernateUserDao;
@Test
public void test01() {
basicUserDao.save();
hibernateUserDao.save();
System.out.println("注解开发执行完毕!");
}
}
3.3.3 注解开发详解
3.3.3.1 @Component
- 该注解用于将一个类交给spring进行管理,该类有三个衍生类:
- @Service:用于事务层
- @Controller:用于Web层
- @Reponsitory:用于持久层
3.3.3.2 属性注入的注解
- @Value:用于注入普通属性
- @Autowired:按照类型完成对象属性的注入
- @Qualifier:它们两个配合完成按照名称的注入
- @Resource:按照名称完成对象属性的注入
3.3.3.3 Bean的其他注解
- @PostConstruct :初始化方法
- @PreDestory:销毁方法
- @Scope:配置作用范围
- singleton:默认的,Spring会采用单例模式创建这个对象。
- prototype:多例模式。。
- request:应用在web项目中,Spring创建这个类以后,将这个类存入到request范围中。
- session:应用在web项目中,Spring创建这个类以后,将这个类存入到session范围中
- globalsession:应用在web项目中,必须在porlet环境下使用。但是如果没有这种环境,相对于session。
3.3.4 xml开发和注解的整合
3.3.4.1 两者的比较
- xml:适用性更广,结构清晰,方便后期管理。
- 注解方式:适用类是自己定义,开发方便,不利于后期管理。
3.3.4.2 整合开发
- 使用xml定义类
- 使用注解完成属性注入
- 使用方式:在配置文件中,将扫描包改成如下即可。
<context:annotation-config />
3.3.5 使用纯注解开发
3.3.5.1 创建注解类
@Configuration
@ComponentScan("com.itheima")
public class SpringConfguration {
}
3.3.5.2 注解详解
- @Configuration:设置类为配置类
- @ComponentScan(“com.itheima”):设置扫描包路径
3.3.6 整合Junit
- 引入
spring-test-4.2.4.RELEASE.jar
包。 - 在测试类上添加如下两个注解
@RunWith(SpringJUnit4ClassRunner.class) //告诉test使用spring提供的的测试类
@ContextConfiguration("classpath:bean.xml") //加载配置文件的位置
- 在测试类里边即可用注解进行属性注入,方便测试。
四、Spring AOP
4.1 什么是AOP
AOP为Aspect Oriented Programming的缩写,意为:面向切面编程。在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,在不改变原有的逻辑的基础上,增加一些额外的功能。
AOP可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善。OOP引入封装、继承、多态等概念来建立一种对象层次结构,用于模拟公共行为的一个集合。不过OOP允许开发者定义纵向的关系,但并不适合定义横向的关系。AOP技术恰恰相反,它利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。
4.2 AOP的术语
Joinpoint :连接点
Pointcut :切入点
Advice :通知
Introduction :引介
Target :目标
Weaving :织入
Proxy :代理对象
Aspect :切面
如果想要的对一个类进行增加功能,即增强功能,那么,以此为媒介,理解相关术语:
可以增强的类的方法被称为连接点(Joinpoint),而真正被增强的方法可以被称为切入点(Pointcut),增强该方法的相关方法被称为是通知(Advice),如果对类进行增强即被称为引介(Introduction)。
在增强之后被增强的对象被称为目标(Target),而将增强的方法应用到被增强的方法上的过程则被称为织入(Weaving),增强的方法被称为该类的代理对象(Proxy),而对该类增强的所有方法的综合被称为切面(Aspect)。
4.3 AOP开发入门
4.3.1 引入jar包
除了要引入基本的六个包以外,还需要引入aop开发的包
4.3.2 编写目标类
public class CustomerServiceImpl implements CustomerService {
@Override
public void save() {
System.out.println("save()执行了!");
}
@Override
public void update(int i) {
System.out.println("update()执行了!");
}
@Override
public boolean delete() {
System.out.println("delete()执行了!");
return false;
}
}
4.3.3 编写切面类
public class Logging {
public void beforePrintLog() {
System.out.println("beforePrintLog日志記錄了。。。");
}
public void afterPrintLog() {
System.out.println("afterPrintLog日志記錄了。。。");
}
public void afterReturningPrintLog() {
System.out.println("afterReturiningPrintLog日志記錄了。。。");
}
public Object aroundPrintLog(ProceedingJoinPoint pjp) {
Object rtValue = null;
try {
System.out.println("aroundPrintLog日志記錄了。。。前置通知");
rtValue = pjp.proceed();
System.out.println("aroundPrintLog日志記錄了。。。后置通知");
} catch (Throwable e) {
System.out.println("aroundPrintLog日志記錄了。。。异常通知");
e.printStackTrace();
}finally {
System.out.println("aroundPrintLog日志記錄了。。。最终通知");
}
return rtValue;
}
public void throwingPrintLog() {
System.out.println("throwingPrintLog日志記錄了。。。");
}
}
4.3.4 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl"/>
<bean id="logging" class="com.itheima.Aspect.Logging"/>
<aop:config>
<aop:aspect id="writeLog" ref="logging" >
<aop:before method="beforePrintLog" pointcut="execution(public void com.itheima.service.impl.CustomerServiceImpl.save())"/>
<aop:after method="afterPrintLog" pointcut="execution(public void com.itheima.service.impl.CustomerServiceImpl.save())"/>
<aop:after-returning method="afterReturningPrintLog" pointcut="execution(public void com.itheima.service.impl.CustomerServiceImpl.save())"/>
<aop:around method="aroundPrintLog" pointcut="execution(public void com.itheima.service.impl.CustomerServiceImpl.save())"/>
<aop:after-throwing method="throwingPrintLog" pointcut="execution(public void com.itheima.service.impl.CustomerServiceImpl.save())"/>
</aop:aspect>
</aop:config>
</beans>
4.3.5 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:beans.xml")
public class AopTest {
@Resource(name="customerService")
private CustomerService customerService;
@Test
public void demo1() {
customerService.save();
}
}
4.4 aop入门总结
4.4.1 配置文件解析
- aop:config 配置aop切面
- aop:pointcut 配置切入点
- id:切入点名称
- expression:配置切入点函数
- execution(权限修饰符 返回值 包名.包名…类名.方法名(参数))
- 其中权限修饰符可以省略,返回值、包名、类名均可以使用*来标识任意,参数可以使用…表示任意参数。
- execution(权限修饰符 返回值 包名.包名…类名.方法名(参数))
- aop:aspect 配置切面
- id:切面id
- ref:被增方法的bean id
- order:优先级
- aop通知方式
- aop:before:前置通知,在被增强方法执行前执行
- aop:after-returning:后置通知,在被增强方法执行后执行
- returning:返回值
- aop:around:环绕通知,是spring为我们提供的一种手动控制执行代码的方式。
- aop:after-throwing:异常通知,在被执行方法出现异常时执行
- throwing:指定异常通知错误信息变量
- aop:after:最终通知,始终在最后执行
- 通用属性:
- method:增强类的增强方法名
- pointcut:切入点
4.5 AOP的注解开发
4.5.1 修改切面类
@Component("logging")
@Aspect
public class Logging {
@Pointcut("execution(public void com.itheima.service.impl.CustomerServiceImpl.save())")
private void pt(){};
@Before("pt()")
public void beforePrintLog() {
System.out.println("beforePrintLog日志記錄了。。。");
}
@After("pt()")
public void afterPrintLog() {
System.out.println("afterPrintLog日志記錄了。。。");
}
@AfterReturning("pt()")
public void afterReturningPrintLog() {
System.out.println("afterReturiningPrintLog日志記錄了。。。");
}
@Around("pt()")
public Object aroundPrintLog(ProceedingJoinPoint pjp) {
Object rtValue = null;
try {
System.out.println("aroundPrintLog日志記錄了。。。前置通知");
rtValue = pjp.proceed();
System.out.println("aroundPrintLog日志記錄了。。。后置通知");
} catch (Throwable e) {
System.out.println("aroundPrintLog日志記錄了。。。异常通知");
e.printStackTrace();
}finally {
System.out.println("aroundPrintLog日志記錄了。。。最终通知");
}
return rtValue;
}
@AfterThrowing("pt()")
public void throwingPrintLog() {
System.out.println("throwingPrintLog日志記錄了。。。");
}
}
4.5.2 修改目标类
@Service("customerService")
public class CustomerServiceImpl implements CustomerService {
...
}
4.5.3 修改配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.itheima"/>
<!-- 开启aop -->
<aop:aspectj-autoproxy/>
</beans>
4.5.4 纯注解开发
只需要在配置类上加上 @EnableAspectJAutoProxy
即可。
五、Spring JdbcTemplate
Spring是EE开发的一站式的框架,对每一层的开发都有解决方案。而对于持久层,Spring提供了ORM模块和JDBC模块。
5.1 JdbcTemplate的入门
5.1.1 引入Jar包
- 引入基本的开发包(略)
- 引入数据库驱动包(
mysql-connector-java-5.1.7-bin.jar
) - 引入Jdbc模板的Jar包(
spring-jdbc-4.2.4.RELEASE.jar
)
5.1.2 创建数据库和表
create database spring_jdbc_test;
use spring_jdbc_test;
create table employee(
id int primary key auto_increment,
name varchar(20),
salary double
);
insert into employee(name,salary) values('aaa',1000);
insert into employee(name,salary) values('bbb',1000);
insert into employee(name,salary) values('ccc',1000);
5.1.3 编写测试类
@Test
public void demo1() {
//配置数据源
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/spring_jdbc_test");
ds.setUsername("root");
ds.setPassword("1234");
//创建JdbcTemplate对象
JdbcTemplate jdbc = new JdbcTemplate();
jdbc.setDataSource(ds);
jdbc.update("insert into employee (name,salary) values('ddd',1234)");
}
5.2 Spring管理JdbcTemplate
5.2.1 创建配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"/>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_jdbc_test" />
<property name="username" value="root"/>
<property name="password" value="1234"/>
</bean>
</beans>
5.2.2 编写测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class JdbcTest {
@Resource(name="jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Resource(name="ds")
private DriverManagerDataSource driverManagerDataSource;
@Test
public void demo2() {
jdbcTemplate.update("insert into employee (name,salary) values('eee',1234)");
}
}
5.2.3 DBCP的使用
- 引入Jar包并修改配置文件(
com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar
/com.springsource.org.apache.commons.pool-1.5.3.jar
)
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"/>
</bean>
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_jdbc_test" />
<property name="username" value="root"/>
<property name="password" value="1234"/>
</bean>
5.2.4 C3P0的使用
- 引入Jar包并修改配置文件(
com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
)
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"/>
</bean>
<bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_jdbc_test" />
<property name="user" value="root"/>
<property name="password" value="1234"/>
</bean>
5.3 使用Dao模拟CRUD操作
5.3.1 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="employeeDao" class="com.itheima.dao.Impl.EmployeeDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"/>
</bean>
<bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_jdbc_test" />
<property name="user" value="root"/>
<property name="password" value="1234"/>
</bean>
</beans>
5.3.2 Dao代码实现
public class EmployeeDaoImpl extends JdbcDaoSupport implements EmployeeDao {
private JdbcTemplate jdbcTemplate;
@Override
public void insert() {
jdbcTemplate.update("insert into employee (name,salary) values('fff',1000)");
}
@Override
public void delete() {
jdbcTemplate.update("delete form employee where id=?",1);
}
@Override
public void update() {
jdbcTemplate.update("update employee set salary=? where id=?",1234d,5);
}
@Override
public void find() {
List<Employee> query = jdbcTemplate.query("select * from employee",new BeanPropertyRowMapper<Employee>(Employee.class));
for (Employee employee : query) {
System.out.println(employee);
}
}
}
5.3.4 总结
dao中的EmployeeDao类继承了spring提供的JdbcDaoSupport类,该类中有JdbcTemplate方法,所以可以使用spring来注入。
六、Spring 事务管理
6.1 事务概览
6.1.1 什么是事务
指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不执行。
6.1.2 事务的特性
- 原子性:事务不可分割
- 一致性:事务执行前后数据完整性保持一致
- 隔离性:一个事务的执行不应该受到其他事务的干扰
- 持久性:一旦事务结束,数据就持久化到数据库
6.1.3 安全问题
-
读问题
- 脏读 :一个事务读到另一个事务未提交的数据
- 不可重复读 :一个事务读到另一个事务已经提交的update的数据,导致一个事务中多次查询结果不一致
- 虚读、幻读 :一个事务读到另一个事务已经提交的insert的数据,导致一个事务中多次查询结果不一致。
-
写问题
- 丢失更新
6.1.4 隔离级别
- Read uncommitted :未提交读,任何读问题解决不了。
- Read committed :已提交读,解决脏读,但是不可重复读和虚读有可能发生。
- Repeatable read :重复读,解决脏读和不可重复读,但是虚读有可能发生。
- Serializable :解决所有读问题。
6.2 spring 事务XML方式
以转账事务为例,检测在有异常的情况下的方式。
6.2.1 导入Jar包
- 导入初始jar包
- 导入mysql连接包
- 导入jdbc+tx包
6.2.2 编写实体类
public class Employee {
private Integer id;
private String name;
private Double salary;
...get/set/toString...
}
6.2.3 编写service类
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDao employeeDao;
public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}
@Override
public Employee findById(Integer id) {
return employeeDao.fingById(id);
}
@Override
public void transferSalary(int from, int to, double money) {
Employee fromEm = findById(from);
Employee toEm = findById(to);
employeeDao.updateSalary(from,fromEm.getSalary() - money);
int i = 1/0;
employeeDao.updateSalary(to,toEm.getSalary() + money);
}
}
6.2.4 编写dao类
public class EmployeeDaoImpl extends JdbcDaoSupport implements EmployeeDao {
@Override
public Employee fingById(Integer id) {
List<Employee> query = getJdbcTemplate().query("select * from employee where id=?", new BeanPropertyRowMapper<Employee>(Employee.class), id);
return query.isEmpty()?null:query.get(0);
}
@Override
public void updateSalary(int id, double money) {
getJdbcTemplate().update("update employee set salary=? where id=?", money,id);
}
}
6.2.5 编写配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="employeeDao" class="com.itheima.dao.impl.EmployeeDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="employeeService" class="com.itheima.service.impl.EmployeeServiceImpl">
<property name="employeeDao" ref="employeeDao"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_jdbc_test"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</bean>
<!-- 配置spring事务 -->
<bean id="transitionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="transitionAdvice" transaction-manager="transitionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt"/>
<aop:advisor advice-ref="transitionAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>
6.2.6 编写测试类
public class Client {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
EmployeeService employeeService = (EmployeeService) ac.getBean("employeeService");
employeeService.transferSalary(2, 4, 100);
}
}
6.2.7 总结
- 配置XML事务的基本步骤:
- 引入tx约束
- 将dao、service交给spring进行管理
- 配置事务管理器
- 配置事务的通知
- 配置aop
- xml配置详解:
- 事务的属性:
- isolation:配置事务的隔离级别,默认值是DEFAULT
- propagation:配置事务的传播行为,默认值是REQUIRED
- timeout:指定事务的超时时间,默认值是-1,永不超时
- read-only:配置事务是否只读,默认值是false
- rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚,产生其他异常时,事务不回滚,没有默认值,任何异常都回滚。
- no-rollback-for:用于指定一个异常,当执行产生该异常时,事务不回滚,产生其他异常时,事务回滚,没有默认值,任何一场都回滚。
- 事务的属性:
- 事务管理API:
- PlatformtransactionManager:平台事务管理器,接口,Spring用于管理事务的真正对象。
- DataSourceTransactionManager:底层使用JDBC管理事务。
- HibernateTransactionManager:得层使用Hibernate管理事务。
- TransactionDefinition:事务定义信息,用于定义事务的相关信息,隔离级别,超时信息,传播行为,是否只读。
- TransactionStatus:事物的状态,用于记录事务管理的过程中,事务状态的对象。
- PlatformtransactionManager:平台事务管理器,接口,Spring用于管理事务的真正对象。
6.3 spring事务注解方式
6.3.1 引入Jar包
- 引入XML方式的jar包
- 引入aop开发的包
6.3.2 修改service
@Transactional(readOnly = false,propagation = Propagation.REQUIRED)
public class EmployeeServiceImpl implements EmployeeService {
@Resource(name="employeeDao")
private EmployeeDao employeeDao;
public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}
...
}
6.3.3 修改dao
@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {
@Resource(name="jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Override
public Employee fingById(Integer id) {
List<Employee> query = jdbcTemplate.query("select * from employee where id=?", new BeanPropertyRowMapper<Employee>(Employee.class), id);
return query.isEmpty()?null:query.get(0);
}
@Override
public void updateSalary(int id, double money) {
jdbcTemplate.update("update employee set salary=? where id=?", money,id);
}
}
6.3.4 修改配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.itheima "/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_jdbc_test"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</bean>
<!-- 配置spring事务 -->
<bean id="transitionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transitionManager"/>
</beans>
6.3.5 纯注解方式
-
删除配置文件
-
创建配置类
- 创建SpringConfiguration
@Configuration @ComponentScan("com.itheima") @EnableTransactionManagement @Import({JdbcConfiguration.class,TransitionConfiguration.class}) public class SpringConfiguration { }
- 创建JdbcConfiguration
public class JdbcConfiguration { @Bean(name="jdbcTemplate") public JdbcTemplate createJdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean(name="dataSource") public DataSource createDataSource() { DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost:3306/spring_jdbc_test"); ds.setUsername("root"); ds.setPassword("1259892859.."); return ds; } }
- 创建TransitionConfiguration
public class TransitionConfiguration { @Bean(name="transitionManager") public PlatformTransactionManager createTransitionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } }
七、SSH整合
SSH整合以客户管理系统为案例进行整合,主要整合三个版本:
- 第一个版本:纯XML方式的整合,保留Spring、struts2、hibernate各自的配置文件;
- 第二个版本:纯XML的整合,保留Spring和struts的主配置文件,hibernate的主配置文件内容配到spring的配置文件中;
- 第三个版本:XML和注解的组合式整合,仅保留Spring的主配置文件(根据开发需要,struts2的配置文件也可以保留)。
主要的整合步骤如下:
第一步:保证Spring的IOC容器能够在web工程中独立运行。
第二步:保证hibernate框架能够在web工程中独立运行。
第三步:整合spring和hibernate。
第四步:保证struts2框架能够在web工程中独立运行。
第五步:整合spring和struts2。
第六步:优化已有的整合配置。配置文件存放位置、配置文件内容分为不同的文件来编写。
所用的所有Jar包如下:
- Spring IOC
- spring AOP
- Spring tx
- hibernate
- struts2
- c3p0
7.1 SSH 1.0
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
- spring 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl">
<property name="custoemerDao" ref="customerDao"></property>
</bean>
<bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hibernatestudy_day03"/>
<property name="username" value="root"/>
<property name="password" value="1234"></property>
</bean>
<bean id="transitionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transitionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>
- struts2配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="customerPackage" extends="struts-default" namespace="/">
<action name="customer_*" class="com.itheima.web.action.CustomerAction" method="{1}">
<result>/jsp/customer/add.jsp</result>
<result name="findAllCustomer">/jsp/customer/list.jsp</result>
</action>
</package>
</struts>
-
hibernate配置文件
- 映射文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.itheima.domain"> <class name="Customer" table="cst_customer"> <id name="cust_id" column="cust_id"> <generator class="native"/> </id> <property name="cust_name" column="cust_name"/> <property name="cust_source" column="cust_source"/> <property name="cust_idustry" column="cust_industry"/> <property name="cust_level" column="cust_level"/> <property name="cust_phone" column="cust_phone"/> <property name="cust_mobile" column="cust_mobile"/> </class> </hibernate-mapping>
- 主配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///hibernatestudy_day03</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">1234</property> <!-- 配置方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <mapping resource="com/itheima/domain/Customer.hbm.xml"/> </session-factory> </hibernate-configuration>
7.2 SSH 2.0
- 配置文件
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring/applicationContext.xml</param-value>
</context-param>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,config/struts/struts.xml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
-
spring配置文件
- applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <import resource="applicationContext-customer.xml"/> <import resource="applicationContext-jdbc.xml"/> <import resource="applicationContext-tx.xml"/> </beans>
- applicationContext-tx.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="transitionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:advice id="txAdvice" transaction-manager="transitionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="false"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/> </aop:config> </beans>
- applicationContext-jdbc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <property name="mappingLocations"> <array> <value>classpath:com/itheima/domain/*.hbm.xml</value> </array> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernatestudy_day03"/> <property name="user" value="root"/> <property name="password" value="1234"></property> </bean> </beans>
- applicationContext-customer.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl"> <property name="custoemerDao" ref="customerDao"></property> </bean> <bean id="customerDao" class="com.itheima.dao.impl.CustomerDaoImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="customerAction" class="com.itheima.web.action.CustomerAction" scope="prototype"> <property name="customerService" ref="customerService"></property> </bean> </beans>
-
struts配置文件
- 主配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="myDefault" extends="struts-default" abstract="true"> </package> <include file="config/struts/struts-customer.xml"></include> </struts>
- struts-customer.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="customerPackage" extends="myDefault" namespace="/customer"> <action name="customer_*" class="customerAction" method="{1}"> <result>/jsp/customer/add.jsp</result> <result name="findAllCustomer">/jsp/customer/list.jsp</result> </action> </package> </struts>
7.3 SSH 3.0
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring/applicationContext.xml</param-value>
</context-param>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,config/struts/struts.xml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
-
dao
- domain
@Entity @Table(name="cst_customer") public class Customer { @Id @Column(name="cust_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long cust_id; @Column(name="cust_name") private String cust_name; @Column(name="cust_source") private String cust_source; @Column(name="cust_industry") private String cust_idustry; @Column(name="cust_level") private String cust_level; @Column(name="cust_phone") private String cust_phone; @Column(name="cust_mobile") private String cust_mobile; ...get/set... }
- dao
@Repository("customerDao") public class CustomerDaoImpl implements CustomerDao { @Resource(name="hibernateTemplate") private HibernateTemplate hibernateTemplate; @Override public List<Customer> findAllCustomer() { return (List<Customer>) hibernateTemplate.find("from Customer"); } @Override public void saveCustomer(Customer customer) { hibernateTemplate.save(customer); } }
-
service
@Service("customerService")
@Transactional(readOnly = false,propagation = Propagation.REQUIRED)
public class CustomerServiceImpl implements CustomerService {
@Resource(name="customerDao")
private CustomerDao customerDao;
@Override
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public List<Customer> findAllCustoemr() {
return customerDao.findAllCustomer();
}
@Override
public void saveCustomer(Customer customer) {
customerDao.saveCustomer(customer);
}
}
- action
@Component("customerAction")
@ParentPackage("struts-default")
@Namespace("/")
@Results({
@Result(name="saveUI",type="dispatcher",location="/jsp/customer/add.jsp" ),
@Result(name="findAllCustomer",type="dispatcher",location="/jsp/customer/list.jsp" )
})
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {
private Customer customer;
@Resource(name="customerService")
private CustomerService customerService;
private List<Customer> customers;
public void setCustomer(Customer customer) {
this.customer = customer;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
@Override
public Customer getModel() {
return customer;
}
@Action("customer_saveUI")
public String saveUI() {
return "saveUI";
}
@Action("customer_findAllCustomer")
public String findAllCustomer() {
customers = customerService.findAllCustoemr();
return "findAllCustomer";
}
}
- spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.itheima"/>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<array>
<value>com.itheima.domain</value>
</array>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernatestudy_day03"/>
<property name="user" value="root"/>
<property name="password" value="1259892859.."></property>
</bean>
<bean id="transitionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transitionManager"/>
</beans>
八、总结
至此,学习完了ssh,做一个阶段性总结。虽然现在的ssh已经没落了,但是思想还是值得学习,主要是了解框架的运行原理,还有就是spring整合的特性。明天开始ssm的学习。如果上述内容有错误,欢迎指正。