一、Spring概述
Spring是一个轻量级的**控制反转(IoC)和面向切面(AOP)**的容器(框架)。
组成:
- 核心容器(core):核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory ,它 是工厂模式的实现。 BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
- 上下文(context):Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文 包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
- Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以 将声明性事务管理集成到应用程序中。
- Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异 常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次 结构。
- Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包 括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
- Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提 供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请 求以及将请求参数绑定到域对象的工作。
- Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口, MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。
二、什么是IOC
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是获得依赖对象的方式反转了。
在spring中,控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。
练习:使用spring框架输出”Hello,Spring!“
1、配置pom.xml文件,导入相关依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
2、创建实体类
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
3、在resources目录下创建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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.wuhangji.pojo.Hello">
<property name="str" value="Hello,spring!"/>
</bean>
</beans>
4、测试
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Hello bean = (Hello) context.getBean("hello");
System.out.println(bean.toString());
}
控制台输出结果:
Hello{str='Hello,spring!'}
在使用spring时,相当于是spring创建了对象并放在它的容器中,当我们需要时就可以从中选择对象。当我们需要再创建其他对象时,只需要在配置文件中配置即可。实现了对象由Spring 来创建 , 管理 , 装配 !
三、IOC创建对象方式
(一)无参构造
上述例子即是无参构造,并且在调用toString方法之前,spring就创建好对象。
(二)有参构造
public class Person {
int id;
String name;
int age;
...
}
方法一:
<bean id="person" class="com.wuhangji.pojo.Person">
<constructor-arg index="0" value="1"/>
<constructor-arg index="1" value="xiaohu"/>
<constructor-arg index="2" value="23"/>
</bean>
方法二:
<bean id="person" class="com.wuhangji.pojo.Person">
<constructor-arg name="id" value="1"/>
<constructor-arg name="name" value="xiaohu"/>
<constructor-arg name="age" value="23"/>
</bean>
方法三:
<bean id="person" class="com.wuhangji.pojo.Person">
<constructor-arg type="int" value="1"/>
<constructor-arg type="java.lang.String" value="xiaohu"/>
<constructor-arg type="int" value="23"/>
</bean>
控制台输出结果:
Person{id=1, name='xiaohu', age=23}
四、spring配置
(一)别名
<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="person" alias="personNew"/>
(二)Bean配置
<!--id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
如果配置id,又配置了name,那么name是别名
name可以设置多个别名,可以用逗号,分号,空格隔开
如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;
class是bean的全限定名=包名+类名
-->
<bean id="hello" name="hello2 h2,h3;h4" class="com.wuhangji.pojo.Hello">
<property name="name" value="Hello,spring!"/>
</bean>
(三)import
<import resource="{path}/beans.xml"/>
五、依赖注入(DI)
- 依赖注入(Dependency Injection,DI)
- 依赖 : 指Bean对象的创建依赖于容器,Bean对象的依赖资源
- 注入 : 指Bean对象所依赖的资源,由容器来设置和装配
(一)构造器注入
见上文
(二)set注入
要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型没有set方法 , 则是 is
1、常量注入
<bean id="student" class="com.wuhangji.pojo.Student">
<property name="name" value="小明"/>
</bean>
2、bean注入
<bean id="addr" class="com.wuhangji.pojo.Address">
<property name="address" value="重庆"/>
</bean>
<bean id="student" class="com.wuhangji.pojo.Student">
<property name="name" value="小明"/>
<property name="address" ref="addr"/>
</bean>
3、数组注入
<bean id="student" class="com.wuhangji.pojo.Student">
<property name="name" value="小明"/>
<property name="address" ref="addr"/>
<property name="books">
<array>
<value>西游记</value>
<value>红楼梦</value>
<value>水浒传</value>
</array>
</property>
</bean>
4、list注入
<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>爬山</value>
</list>
</property>
5、map注入
<property name="card">
<map>
<entry key="中国邮政" value="456456456465456"/>
<entry key="建设" value="1456682255511"/>
</map>
</property>
6、set注入
<property name="games">
<set>
<value>LOL</value>
<value>BOB</value>
<value>COC</value>
</set>
</property>
7、null注入
<property name="wife"><null/></property>
8、properties注入
<property name="info">
<props>
<prop key="学号">20190604</prop>
<prop key="性别">男</prop>
<prop key="姓名">小明</prop>
</props>
</property>
控制台输出结果:
name=小明,address=重庆,books=
<<西游记>> <<红楼梦>> <<水浒传>>
爱好:[听歌, 看电影, 爬山]
card:{中国邮政=456456456465456, 建设=1456682255511}
games:[LOL, BOB, COC]
wife:null
info:{学号=20190604, 性别=男, 姓名=小明}
(三)拓展注入
1、P命名空间注入
导入约束 : xmlns:p="http://www.springframework.org/schema/p"
<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.wuhangji.pojo.User" p:name="xiaoming" p:age="18"/>
2、c命名空间注入
导入约束 : xmlns:c="http://www.springframework.org/schema/c"
<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法,需要有参或者无参构造器-->
<bean id="user" class="com.wuhangji.pojo.User" c:name="xiaoming" c:age="18"/>
六、Bean的作用域
在配置文件中,可以通用 scope 属性配置作用域:
<bean id="User" class="com.wuhangji.pojo.User" scope="singleton">
(一)Singleton
在Spring容器中只存在一个bean实例,以单例形式存在,默认值。
(二)Prototype
每次从容器中取出bean都不会是同一个bean,会返回一个新的实例。
(三)Request
每次请求都会创建一个新的bean实例。
(四)Session
同一个session中共享同一个bean,不同的session的bean不相同。
七、Bean的自动装配
上文我们的例子都是在xml配置文件中装配对象。接下来介绍一下bean的自动装配。
Spring的自动装配需要从两个角度来实现,或者说是两个操作:
- 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
- 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;
(一)配置环境
public class Dog {
public void barking(){
System.out.println("汪汪~~");
}
}
public class Cat {
public void barking(){
System.out.println("喵喵~~");
}
}
public class Person {
String name;
Cat cat;
Dog dog;
...
}
<bean id="dog" class="com.wuhangji.pojo.Dog"/>
<bean id="cat" class="com.wuhangji.pojo.Cat"/>
<bean id="person" class="com.wuhangji.pojo.Person">
<property name="name" value="小明"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
(二)自动装配xml配置
1、byName
<bean id="person" class="com.wuhangji.pojo.Person" autowire="byName">
<property name="name" value="小明"/>
</bean>
当一个bean节点带有 autowire="byName"的属性时:
- 将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
- 去spring容器中寻找是否有此字符串名称id的对象。
- 如果有,就取出注入;如果没有,就报空指针异常。
2、byType
<bean id="person" class="com.wuhangji.pojo.Person" autowire="byType">
<property name="name" value="小明"/>
</bean>
当一个bean节点带有 autowire="byType"的属性时:
需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报异常。
(三)注解
准备工作: 利用注解的方式注入属性。
- 在spring配置文件中引入context文件头
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
- 开启属性注解支持
<context:annotation-config/>
1、@Autowired
在Person类中我们就可以把set方法全部删掉,并且加上注解。
public class Person {
String name;
@Autowired
Cat cat;
@Autowired
Dog dog;
public Cat getCat() {
return cat;
}
public Dog getDog() {
return dog;
}
}
<bean id="dog" class="com.wuhangji.pojo.Dog"/>
<bean id="cat" class="com.wuhangji.pojo.Cat"/>
<bean id="person" class="com.wuhangji.pojo.Person"/>
2、@Qualifier
-
@Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配
-
@Qualifier不能单独使用。
如果我们有多个class相同但name不同的类,我们可以加上@Qualifier来却确定要创建哪一个类
<bean id="dog" class="com.wuhangji.pojo.Dog"/>
<bean id="cat" class="com.wuhangji.pojo.Cat"/>
<bean id="dog22" class="com.wuhangji.pojo.Dog"/>
<bean id="person" class="com.wuhangji.pojo.Person"/>
@Autowired
@Qualifier(value = "dog22")
Dog dog;
3、@Resource
- @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
- 其次再进行默认的byName方式进行装配;
- 如果以上都不成功,则按byType的方式自动装配。
八、使用注解开发
(一)bean实现
配置context约束,开启注解配置,注解扫描
<?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"
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:annotation-config/>
<context:component-scan base-package="com.wuhangji.pojo"/>
</beans>
创建实体类
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
public String name = "小明";
}
测试
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
System.out.println(user.name);
}
控制台输出:
小明
(二)属性注入
- 可以不用提供set方法,直接在直接名上添加@value(“值”)
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
@Value("小红")
// 相当于配置文件中 <property name="name" value="小红"/>
public String name;
}
- 如果提供了set方法,在set方法上添加@value(“值”)
@Component("user")
public class User {
public String name;
@Value("小红")
public void setName(String name) {
this.name = name;
}
}
(三)衍生注解
@Component三个衍生注解
- @Controller:web层
- @Service:service层
- @Repository:dao层
Spring可以使用其它三个注解,功能一样,实现了更好的进行分层。
(四)作用域
@scope
- singleton:默认,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁;
- prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Controller("user")
@Scope("prototype")
public class User {
@Value("小红")
public String name;
}
(五)基于Java类进行配置
创建一个Dog类
@Component
public class Dog {
String name = "dog";
}
创建一个包 com.wuhangji.config ,创建一个 MyConfig 类
@Configuration
public class MyConfig {
@Bean //通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
public Dog getDog(){
return new Dog();
}
}
@Test
public void test2(){
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
Dog dog = context.getBean("getDog", Dog.class);
System.out.println(dog.name);
}
我们还可以使用@Import导入其他配置类
@Configuration
@Import(MyConfig2.class) //导入合并其他配置类,类似于配置文件中的 inculde 标签
public class MyConfig {
@Bean
public Dog dog(){
return new Dog();
}
}
九、代理模式
(一)静态代理
具体详情看大话设计模式之静态代理模式
(二)动态代理
具体详情看大话设计模式之动态代理模式
十、AOP
(一)什么是AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
(二)AOP在Spring中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要 关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …
- 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知执行的 “地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点
(三)实现AOP
准备:导入相关依赖和约束
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
1、方式一:Spring API实现
编写业务接口和实现类
public interface UserService {
public void add();
public void delete();
public void update();
public void search();
}
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增加用户");
}
public void delete() {
System.out.println("删除用户");
}
public void update() {
System.out.println("更新用户");
}
public void search() {
System.out.println("查询用户");
}
}
编写前置增强和后置增强
public class LogBefore implements MethodBeforeAdvice {
//method : 要执行的目标对象的方法
//objects : 被调用的方法的参数
//o : 目标对象
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println( o.getClass().getName() + "的" + method.getName()
+ "方法被执行了");
}
}
public class LogAfter implements AfterReturningAdvice {
//o 返回值
//method被调用的方法
//objects 被调用的方法的对象的参数
//o1 被调用的目标对象
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了" + o1.getClass().getName()
+"的"+method.getName()+"方法,"
+"返回值:"+o);
}
}
在Spring配置文件中注册
<bean id="userService" class="com.wuhangji.service.impl.UserServiceImpl"/>
<bean id="logBefore" class="com.wuhangji.pojo.LogBefore"/>
<bean id="logAfter" class="com.wuhangji.pojo.LogAfter"/>
<aop:config>
<aop:pointcut id="pointCut"
<!--切入点 expression:表达式匹配要执行的方法-->
<!--修饰词,返回值,类名,参数-->
expression="execution(* com.wuhangji.service.impl.UserServiceImpl.*(..))"/>
<!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
<aop:advisor advice-ref="logBefore" pointcut-ref="pointCut"/>
<aop:advisor advice-ref="logAfter" pointcut-ref="pointCut"/>
</aop:config>
测试:
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
控制台输出:
com.wuhangji.service.impl.UserServiceImpl的add方法被执行了
增加用户
执行了com.wuhangji.service.impl.UserServiceImpl的add方法,返回值:null
2、方式二:自定义切类实现
自定义一个切面类
public class MyPointCut {
public void before(){
System.out.println("---------方法执行前---------");
}
public void after(){
System.out.println("---------方法执行后---------");
}
}
在Spring配置文件中注册
<bean id="diy" class="com.wuhangji.pojo.MyPointCut"/>
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="pointCut"
expression="execution(* com.wuhangji.service.impl.UserServiceImpl.*(..))"/>
<aop:before pointcut-ref="pointCut" method="before"/>
<aop:after pointcut-ref="pointCut" method="after"/>
</aop:aspect>
</aop:config>
测试:
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
控制台输出:
---------方法执行前---------
增加用户
---------方法执行后---------
3、方式三:使用注解实现
第一步:编写一个注解实现的增强类
@Aspect
public class AnnotationPointCut {
@Before("execution(* com.wuhangji.service.impl.UserServiceImpl.*(..))")
public void before(){
System.out.println("---------方法执行前---------");
}
@After("execution(* com.wuhangji.service.impl.UserServiceImpl.*(..))")
public void after(){
System.out.println("---------方法执行后---------");
}
@Around("execution(* com.wuhangji.service.impl.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
System.out.println("签名:"+jp.getSignature());
//执行目标方法proceed
Object proceed = jp.proceed();
System.out.println("环绕后");
System.out.println(proceed);
}
}
第二步:在Spring配置文件中,注册bean,并增加支持注解的配置
<bean id="annotationPointCut" class="com.wuhangji.pojo.AnnotationPointCut"/>
<aop:aspectj-autoproxy/>
控制台输出:
环绕前
签名:void com.wuhangji.service.UserService.add()
---------方法执行前---------
增加用户
---------方法执行后---------
环绕后
null
十一、整合MyBatis
准备工作:导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
按照mybatis的正常流程,搭建一个常规的mybatis框架
测试:
@Test
public void test1(){
SqlSession session = MyBatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> list = mapper.getAllUser();
for (User user : list) {
System.out.println(user);
}
}
控制台输出结果:
User{id=1, name='张三', password='123456'}
User{id=2, name='李四', password='10010'}
User{id=3, name='马云', password='10086'}
User{id=4, name='小明', password='12345'}
(一)MyBatis-Spring学习
相关文档: http://www.mybatis.org/spring/zh/index.html
要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:一个 SqlSessionFactory 和至少一个数据映射器类。 在 MyBatis-Spring 中,可使用 SqlSessionFactoryBean 来创建 SqlSessionFactory 。 要配置 这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中:
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
注意: SqlSessionFactory 需要一个 DataSource (数据源)。 这可以是任意的 DataSource ,只需要和配置其它 Spring 数据库连接一样配置它就可以了。
-
在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory 的。 而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来创建。
-
在 MyBatis 中,你可以使用 SqlSessionFactory 来创建 SqlSession 。一旦你获得一个 session 之后,你可以使用它来执行映射了的语句,提交或回滚连接,最后,当不再需要它的时候,你可以关闭 session。
-
SqlSessionFactory 有一个唯一的必要属性:用于 JDBC 的 DataSource 。这可以是任意的 DataSource 对象,它的配置方法和其它 Spring 数据库连接是一样的。 一个常用的属性是 configLocation ,它用来指定 MyBatis 的 XML 配置文件路径。它在需要修改 MyBatis 的基础配置非常有用。通常,基础配置指的是settings或typeAliases元素。 需要注意的是,这个配置文件并不需要是一个完整的 MyBatis 配置。确切地说,任何环境配置 (environments),数据源(DataSource)和 MyBatis 的事务管理器 (transactionManager)都会被忽略。 SqlSessionFactoryBean 会创建它自有的 MyBatis 环境配置( Environment ),并按要求设置自定义环境的值。
-
SqlSessionTemplate 是 MyBatis-Spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession 。 模板可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,最好使用 SqlSessionTemplate 来替换 MyBatis 默认的 DefaultSqlSession 实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。
可以使用 SqlSessionFactory 作为构造方法的参数来创建 SqlSessionTemplate 对象。
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
现在,这个 bean 就可以直接注入到你的 DAO bean 中了。你需要在你的 bean 中添加一个 SqlSession 属性,就像下面这样:
public class UserDaoImpl implements UserDao {
private SqlSession sqlSession;
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
public User getUser(String userId) {
return sqlSession.getMapper...;
}
}
按下面这样,注入 SqlSessionTemplate :
<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">
<property name="sqlSession" ref="sqlSession" />
</bean>
(二)整合实现一
- 在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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
-
配置数据源替换mybaits的数据源
<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/mybatis?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="abc123"/> </bean>
-
配置SqlSessionFactory,关联MyBatis
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="mybatis-config.xml"/>
<property name="mapperLocations" value="mappers/userMapper.xml"/>
</bean>
-
注册sqlSessionTemplate,关联sqlSessionFactory
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
-
增加Dao接口的实现类;私有化sqlSessionTemplate
public class UserMapperImpl implements UserMapper { //sqlSession不用我们自己创建了,Spring来管理 private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } public List<User> getAllUser() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.getAllUser(); } }
-
注册bean实现
<bean id="userMapper" class="com.wuhangji.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
-
测试
@Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); List<User> list = userMapper.getAllUser(); for (User user : list) { System.out.println(user); } } 控制台输出: User{id=1, name='张三', password='123456'} User{id=2, name='李四', password='10010'} User{id=3, name='马云', password='10086'} User{id=4, name='小明', password='12345'}
(三)整合实现二
SqlSessionDaoSupport 是一个抽象的支持类,用来提供 SqlSession。调用 getSqlSession()方法会得到一个 SqlSessionTemplate。
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> getAllUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.getAllUser();
}
}
<bean id="userMapper" class="com.wuhangji.mapper.UserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
十二、声明式事务
(一)什么是事务
事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。
事务四个属性ACID
- 原子性(atomicity) 事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用 ;
- 一致性(consistency) 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中;
- 隔离性(isolation) 可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏;
- 持久性(durability) 事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中
(二)spring中的事务管理
Spring支持编程式事务管理和声明式事务管理。
- 编程式事务管理:将事务管理代码嵌到业务方法中来控制事务的提交和回滚,缺点是必须在每个事务操作业务逻辑中包含额外的事务管理代码
- 声明式事务管理:一般情况下比编程式事务好用。 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。
导入约束:
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
事务管理器 无论使用Spring的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。 就是 Spring的核心事务管理抽象,管理封装了一组独立于技术的方法。
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
spring事务传播特性: 事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。
spring支持7种事务传播行为:
- propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这 个事务中,这是最常见的选择。
- propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
- propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
- propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
- propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
- propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
- propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与 propagation_required类似的操作
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="search*" propagation="REQUIRED"/>
<tx:method name="get" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
配置AOP
<!--配置aop织入事务-->
<aop:config>
<aop:pointcut id="txPointcut"
expression="execution(* com.kuang.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>