Spring框架
Spring框架
Spring是一个开源框架,为简化企业级开发而生。它以IOC(控制反转)和AOP(面向切面)为思想内核,提供了控制层SpringMVC、数据层SpringData、服务层事务管理等众多技术,并可以整合众多第三方框架。
Spring将很多复杂的代码变得优雅简洁,有效的降低代码的耦合度,极大的方便项目的后期维护、升级和扩展。
Spring官网地址:https://spring.io/
Spring体系结构
Spring框架根据不同的功能被划分成了多个模块,这些模块可以满足一切企业级应用开发的需求,在开发过程中可以根据需求有选择性地使用所需要的模块。
- Core Container:Spring核心模块,任何功能的使用都离不开该模块,是其他模块建立的基础。
- Data Access/Integration:该模块提供了数据持久化的相应功能。
- Web:该模块提供了web开发的相应功能。
- AOP:提供了面向切面编程实现
- Aspects:提供与AspectJ框架的集成,该框架是一个面向切面编程框架。
- Instrumentation:提供了类工具的支持和类加载器的实现,可以在特定的应用服务器中使用。
- Messaging:为Spring框架集成一些基础的报文传送应用
- Test:提供与测试框架的集成
IOC_控制反转思想
IOC(Inversion of Control) :程序将创建对象的权利交给框架。
之前在开发过程中,对象实例的创建是由调用者管理的,代码如下:
public interface StudentDao { Student findById(int id); }
public class StudentDaoImpl implements StudentDao{ @Override public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
public class StudentService { public Student findStudentById(int id){ StudentDao studentDao = new StudentDaoImpl(); return studentDao.findById(1); } }
|
这种写法有两个缺点:
1.浪费资源:StudentService调用方法时即会创建一个对象,如果不断调用方法则会创建大量StudentDao对象
2.代码耦合度高:假设随着开发,我们创建了StudentDao另一个更加完善的实现类StudentDaoImpl2,如果在StudentService中想使用StudentDaoImpl2,则必须修改源码。
而IOC思想是将创建对象的权利交给框架,框架会帮助我们创建对象,分配对象的使用,控制权由程序代码转移到了框架中,控制权发生了反转,这就是Spring的IOC思想。而IOC思想可以完美的解决以上两个问题。
IOC_自定义对象容器
接下来我们通过一段代码模拟IOC思想。创建一个集合容器,先将对象创建出来放到容器中,需要使用对象时,只需要从容器中获取对象即可,而不需要重新创建,此时容器就是对象的管理者。
1.创建实体类
package com.itbaizhan.domain;
public class Student { private int id; private String name; private String address;
@Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", address='" + address + '\'' + '}'; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
public Student() { }
public Student(int id, String name, String address) { this.id = id; this.name = name; this.address = address; } }
|
2.创建Dao接口和实现类
package com.itbaizhan.dao;
import com.itbaizhan.domain.Student;
public interface StudentDao { Student findById(int id); }
|
package com.itbaizhan.dao;
import com.itbaizhan.domain.Student;
public class StudentDaoImpl implements StudentDao { @Override public Student findById(int id) { return new Student(1,"百战陈虚谷元","北京"); } }
|
package com.itbaizhan.dao;
import com.itbaizhan.domain.Student;
public class StudentDaoImpl2 implements StudentDao { @Override public Student findById(int id) { System.out.println("新方法!"); return new Student(1,"百战陈虚谷元","北京"); } }
|
3.创建配置文件bean.properties,该文件中定义管理的对象
studentDao=com.itbaizhan.dao.StudentDaoImpl
|
4.创建容器管理类,该类在类加载时读取配置文件,将配置文件中配置的对象全部创建并放入容器中
package com.itbaizhan.container;
import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties;
public class Container { static Map<String,Object> map = new HashMap<>(); static { InputStream is = Container.class.getClassLoader().getResourceAsStream("bean.properties"); Properties properties = new Properties(); try { properties.load(is); Enumeration<Object> keys = properties.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement().toString(); String value = properties.getProperty(key); Object o = Class.forName(value).newInstance(); map.put(key,o); }
} catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } public static Object getBean(String key) { return map.get(key); } }
|
5.创建Dao对象的调用者StudentService
package com.itbaizhan.service;
import com.itbaizhan.container.Container; import com.itbaizhan.dao.StudentDao; import com.itbaizhan.dao.StudentDaoImpl; import com.itbaizhan.domain.Student;
public class StudentService { public Student findStudentById(int id) { StudentDao studentDao = (StudentDao) Container.getBean("studentDao"); System.out.println(studentDao.hashCode()); return studentDao.findById(id); } }
|
6.测试StudentService
package com;
import com.itbaizhan.service.StudentService;
public class Test { public static void main(String[] args) { StudentService studentService = new StudentService(); System.out.println(studentService.findStudentById(1)); System.out.println(studentService.findStudentById(1)); } }
|
测试结果:
StudentService从容器中每次拿到的都是同一个StudentDao对象,节约了资源。
如果想使用StudentDaoImpl2对象,只需要修改bean.properties的内容为即可,无需修改Java源码。
studentDao=com.itbaizhan.dao.StudentDaoImpl2
|
IOC_Spring实现IOC
接下来我们使用Spring实现IOC,Spring内部也有一个容器用来管理对象。
1.创建Maven工程,引入依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.itbaizhan</groupId> <artifactId>spring_ioc1</artifactId> <version>1.0-SNAPSHOT</version>
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.13</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> </project>
|
2.创建POJO类,Dao类和接口
public class Student { private int id; private String name; private String address; }
public interface StudentDao { Student findById(int id); }
public class StudentDaoImpl implements StudentDao{ @Override public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
|
3.编写xml配置文件,放在resource目录下。配置文件中配置需要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"> <bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean> </beans>
|
4.测试从Spring容器中获取对象
package com.itbaizhan;
import com.itbaizhan.dao.StudentDao; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestContainer { @Test public void t1() { ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao"); StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao"); System.out.println(studentDao1.hashCode()); System.out.println(studentDao2.hashCode()); System.out.println(studentDao1.findById(1)); } }
|
IOC_Spring容器类型
容器接口
BeanFactory:BeanFactory是Spring容器中的顶层接口,它可以对Bean对象进行管理。
ApplicationContext:ApplicationContext是BeanFactory的子接口。它除了继承 BeanFactory的所有功能外,还添加了对国际化、资源访问、事件传播等方面的良好支持。
ApplicationContext有以下三个常用实现类:
容器实现类
- ClassPathXmlApplicationContext:该类可以从项目中读取配置文件
- FileSystemXmlApplicationContext:该类从磁盘中读取配置文件
- AnnotationConfigApplicationContext:使用该类不读取配置文件,而是会读取注解
package com.itbaizhan;
import com.itbaizhan.dao.StudentDao; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestContainer { @Test public void t1() {
ApplicationContext ac = new FileSystemXmlApplicationContext("E:\\Eclipse_workspace1\\springdemo\\spring_ioc1\\src\\main\\resources\\bean.xml"); StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao"); StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao"); System.out.println(studentDao1.hashCode()); System.out.println(studentDao2.hashCode()); System.out.println(studentDao1.findById(1)); } }
|
IOC_对象的创建方式
Spring会帮助我们创建bean,那么它底层是调用什么方法进行创建的呢?
使用空参构造方法
Spring默认使用类的空参构造方法创建bean:
public class StudentDaoImpl implements StudentDao{ public StudentDaoImpl(int a){} @Override public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
|
此时将无法完成bean的创建,因为存在有参的构造方法
使用工厂类的方法
Spring可以调用工厂类的方法创建bean:
1.创建工厂类,工厂类提供创建对象的方法:
package com.itbaizhan.dao;
public class StudentDaoFactory { public StudentDao getStudentDao() { return new StudentDaoImpl(1); } }
|
2.在配置文件中配置创建bean的方式为工厂方式
<bean id="studentDaoFactory" class="com.itbaizhan.dao.StudentDaoFactory"></bean>
<bean id="studentDao" factory-bean="studentDaoFactory" factory-method="getStudentDao"></bean>
|
使用工厂类的静态方法
Spring可以调用工厂类的静态方法创建bean:
1.创建工厂类,工厂提供创建对象的静态方法。
package com.itbaizhan.dao;
public class StudentDaoFactory2 { public static StudentDao getStudentDao() { return new StudentDaoImpl(1); } }
|
2.在配置文件中配置创建bean的方式为工厂静态方法。
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoFactory2" factory-method="getStudentDao2"></bean>
|
<?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="studentDao" class="com.itbaizhan.dao.StudentDaoFactory2" factory-method="getStudentDao"></bean> </beans>
|
Spring可以使用这三种方法创建bean对象:静态工厂方法、工厂方法以及空参构造方法
IOC_对象的创建策略
Spring通过配置<bean>
中的scope
属性设置对象的创建策略,共有五种创建策略:
singleton:单例,默认策略。整个项目只会创建一个对象,通过<bean>
中的lazy-init
属性可以设置单例对象的创建时机:
lazy-init=”false”(默认):立即创建,在容器启动时会创建配置文件中的所有Bean对象。
lazy-init=”true”:延迟创建,第一次使用Bean对象时才会创建。
配置单例策略:
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="singleton" lazy-init="false"></bean>
|
测试单例策略:
public StudentDaoImpl2(){ System.out.println("创建StudentDao!!!"); }
@Test public void t2(){ ApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml"); StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao"); StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao"); StudentDao studentDao3 = (StudentDao) ac.getBean("studentDao"); System.out.println(studentDao1.hashCode()); System.out.println(studentDao2.hashCode()); System.out.println(studentDao3.hashCode()); }
|
<?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="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="singleton"></bean>
</beans>
|
prototype:多例,每次从容器中获取时都会创建对象。
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="prototype"></bean>
|
request:每次请求创建一个对象,只在web环境有效。
session:每次会话创建一个对象,只在web环境有效。
gloabal-session:一次集群环境的会话创建一个对象,只在web环境有效。
IOC_对象的销毁时机
对象的创建策略不同,销毁时机也不同:
- singleton:对象随着容器的销毁而销毁。
- prototype:使用JAVA垃圾回收机制销毁对象。
- request:当处理请求结束,bean实例将被销毁。
- session:当HTTP Session最终被废弃的时候,bean也会被销毁掉。
- gloabal-session:集群环境下的session销毁,bean实例也将被销毁。
IOC_生命周期方法
Bean对象的生命周期包含创建——使用——销毁,Spring可以配置Bean对象在创建和销毁时自动执行的方法:
1.定义生命周期方法
package com.itbaizhan.dao;
import com.itbaizhan.domain.Student;
public class StudentDaoImpl2 implements StudentDao{ public StudentDaoImpl2() { System.out.println("create StudentDao"); }
public void init() { System.out.println("create StudentDao-------"); }
public void destory(){ System.out.println("destroy StudentDao!!!"); }
@Override public Student findById(int id) { System.out.println("new Method"); return new Student(1,"baizhanchengxuyuan","Beijing"); } }
|
2.配置生命周期方法
<?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="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="singleton" init-method="init" destroy-method="destory"></bean>
</beans>
|
3.测试
@Test public void t3() { ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml"); ac.close();
}
|
IOC_获取Bean对象的方式
Spring有多种获取容器中对象的方式:
通过id/name获取
1.配置文件
<bean name="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2"></bean> <bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2"></bean>
|
2.获取对象
StudentDao studentDao = (StudentDao) ac.getBean("studentDao");
|
通过class类型获取
1.配置文件
<bean name="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2"></bean>
|
2.获取对象
StudentDao studentDao2 = ac.getBean(StudentDao.class);
|
可以看到使用类型获取不需要强转。
通过类型+id/name获取
虽然使用类型获取不需要强转,但如果在容器中有一个接口的多个实现类对象,则获取时会报错,此时需要使用类型+id/name获取
1.配置文件
<bean name="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2"></bean> <bean name="studentDao1" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
|
2.获取对象
StudentDao studentDao2 = ac.getBean("studentDao",StudentDao.class);
|
DI_什么是依赖注入
依赖注入(Dependency Injection,简称DI),它是Spring控制反转思想的具体实现。
控制反转将对象的创建交给了Spring,但是对象中可能会依赖其他对象。比如service类中要有dao类的属性,我们称service依赖于dao。之前需要手动注入属性值,代码如下:
public interface StudentDao { Student findById(int id); }
public class StudentDaoImpl implements StudentDao{ @Override public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
public class StudentService { private StudentDao studentDao = new StudentDaoImpl(); public Student findStudentById(int id){ return studentDao.findById(id); } }
|
此时,当StudentService的想要使用StudentDao的另一个实现类如StudentDaoImpl2时,则需要修改Java源码,造成代码的可维护性降低。
而使用Spring框架后,Spring管理Service对象与Dao对象,此时它能够为Service对象注入依赖的Dao属性值。这就是Spring的依赖注入。
简单来说,控制反转是创建对象,依赖注入是为对象的属性赋值
DI_依赖注入方式
在之前开发中,可以通过setter方法或构造方法设置对象属性值:
StudentService studentService = new StudentService(); StudentDao studentDao = new StudentDao(); studentService.setStudentDao(studentDao);
StudentDao studentDao = new StudentDao(); StudentService studentService = new StudentService(studentDao);
|
Spring可以通过调用setter方法或构造方法给属性赋值
Setter注入
1.被注入类编写属性的setter方法
package com.itbaizhan.service;
import com.itbaizhan.dao.StudentDao; import com.itbaizhan.domain.Student;
public class StudentService { private StudentDao studentDao;
public StudentDao getStudentDao() { return studentDao; }
public void setStudentDao(StudentDao studentDao) { this.studentDao = studentDao; }
public Student findStudentById(int id) { return studentDao.findById(id); }
}
|
2.配置文件中,给需要注入属性值的中设置
<?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="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean> <bean id="studentService" class="com.itbaizhan.service.StudentService"> <property name="studentDao" ref="studentDao"></property> </bean>
</beans>
|
3.编写测试类
@Test public void t2(){ ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); StudentService studentService = (StudentService) ac.getBean("studentService"); System.out.println(studentService.findStudentById(1)); }
|
构造方法注入
1.被注入类编写有参的构造方法
public class StudentService { private StudentDao studentDao; public StudentService(StudentDao studentDao) { this.studentDao = studentDao; } }
|
2.给需要注入属性值的中设置
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean> <bean id="studentService" class="com.itbaizhan.service.StudentService"> <constructor-arg name="studentDao" ref="studentDao"></constructor-arg> </bean>
|
3.编写测试文件
@Test public void t2(){ ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); StudentService studentService = (StudentService) ac.getBean("studentService"); System.out.println(studentService.findStudentById(1)); }
|
自动注入(个人喜欢的是构造器注入)
自动注入不需要在<bean>
标签中添加其他标签注入属性值,而是自动从容器中找到相应的bean对象设置为属性值。
自动注入有两种配置方式:
- 全局配置:在
<beans>
中设置default-autowire
属性可以定义所有bean对象的自动注入策略。
- 局部配置:在
<bean>
中设置autowire
属性可以定义当前bean对象的自动注入策略。
autowire的取值如下:
no:不会进行自动注入。
default:全局配置default相当于no,局部配置default表示使用全局配置
byName:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供set方法。
byType:在Spring容器中查找类型与属性类型相同的bean,并进行注入。需要提供set方法。
constructor:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供构造方法。
(推荐使用Constructor)
测试自动注入:
1.为依赖的对象提供setter和构造方法:
public class StudentService { private StudentDao studentDao; public StudentService() { }
public StudentService(StudentDao studentDao) { this.studentDao = studentDao; }
public void setStudentDao(StudentDao studentDao) { this.studentDao = studentDao; }
public Student findStudentById(int id) { return studentDao.findById(id); } }
|
2.配置自动注入:
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean> <bean id="studentService" class="com.itbaizhan.service.StudentService" autowire="byName"></bean>
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean> <bean id="studentService" class="com.itbaizhan.service.StudentService" autowire="byType"></bean>
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean> <bean id="studentService" class="com.itbaizhan.service.StudentService" autowire="constructor"></bean>
<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" default-autowire="constructor">
|
DI_依赖注入类型
DI支持注入bean类型、基本数据类型和字符串、List集合、Set集合、Map集合、Properties对象类型等,他们的写法如下:
1.准备注入属性的类:
package com.itbaizhan.service;
import com.itbaizhan.dao.StudentDao; import com.itbaizhan.domain.Student;
import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set;
public class StudentService { private StudentDao studentDao; private String name; private int count; private List<String> names; private List<Student> students1; private Set<Student> students2; private Map<String,String> names2; private Map<String,Student> students3; private Properties properties;
@Override public String toString() { return "StudentService{" + "studentDao=" + studentDao + ", name='" + name + '\'' + ", count=" + count + ", names=" + names + ", students1=" + students1 + ", students2=" + students2 + ", names2=" + names2 + ", students3=" + students3 + ", properties=" + properties + '}'; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getCount() { return count; }
public void setCount(int count) { this.count = count; }
public List<String> getNames() { return names; }
public void setNames(List<String> names) { this.names = names; }
public List<Student> getStudents1() { return students1; }
public void setStudents1(List<Student> students1) { this.students1 = students1; }
public Set<Student> getStudents2() { return students2; }
public void setStudents2(Set<Student> students2) { this.students2 = students2; }
public Map<String, String> getNames2() { return names2; }
public void setNames2(Map<String, String> names2) { this.names2 = names2; }
public Map<String, Student> getStudents3() { return students3; }
public void setStudents3(Map<String, Student> students3) { this.students3 = students3; }
public Properties getProperties() { return properties; }
public void setProperties(Properties properties) { this.properties = properties; }
public StudentService(StudentDao studentDao) { this.studentDao = studentDao; }
public StudentService() { } public StudentDao getStudentDao() { return studentDao; }
public void setStudentDao(StudentDao studentDao) { this.studentDao = studentDao; }
public Student findStudentById(int id) { return studentDao.findById(id); }
}
|
2.准备测试方法
@Test public void t3(){ ApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml"); StudentService studentService = (StudentService)ac.getBean("studentService"); System.out.println(studentService); }
|
注入bean类型
写法一:
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean> <bean id="studentService" class="com.itbaizhan.service.StudentService"> <property name="studentDao" ref="studentDao"></property> </bean>
|
写法二:
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean> <bean id="studentService" class="com.itbaizhan.service.StudentService"> <property name="studentDao" > <ref bean="studentDao"></ref> </property> </bean>
|
注入基本数据类型
<?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="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean> <bean id="studentService" class="com.itbaizhan.service.StudentService"> <property name="studentDao" ref="studentDao"></property>
<property name="name" value="百战"></property> <property name="count"> <value>10</value> </property> </bean>
</beans>
|
注入list集合 (记得,属性是写在bean里面的)
<bean id="studentService" class="com.itbaizhan.service.StudentService">
<property name="names"> <list> <value>尚学堂</value> <value>百战程序员</value> </list> </property>
<property name="students1"> <list> <bean class="com.itbaizhan.domain.Student"> <property name="name" value="rust"/> <property name="id" value="1"/> <property name="address" value="zq"/> </bean>
<bean class="com.itbaizhan.domain.Student"> <property name="name" value="rustB"/> <property name="id" value="2"/> <property name="address" value="zqzg"/> </bean> </list> </property> </bean>
|
注入Set集合
<bean id="studentService" class="com.itbaizhan.service.StudentService">
<property name="students2" > <set> <bean class="com.itbaizhan.domain.Student"> <property name="name" value="apple"/> <property name="id" value="10"/> <property name="address" value="fsfs"/> </bean>
<bean class="com.itbaizhan.domain.Student"> <property name="name" value="kingdom"/> <property name="id" value="56"/> <property name="address" value="aaaa"/> </bean> </set> </property> </bean>
|
注入Map集合
简单数据类型Map集合:
<bean id="studentService" class="com.itbaizhan.service.StudentService"> <property name="names2"> <map> <entry key="student1" value="bz"/> <entry key="student2" value="sxt"/> </map> </property> </bean>
|
对象类型Map集合:
<bean id="studentService" class="com.itbaizhan.service.StudentService"> <property name="students3"> <map> <entry key="student1" value-ref="s1"></entry> <entry key="student2" value-ref="s2"></entry> </map> </property> </bean> <bean id="s1" class="com.itbaizhan.domain.Student"> <property name="id" value="1"/> <property name="name" value="尚学堂"/> <property name="address" value="北京"/> </bean>
<bean id="s2" class="com.itbaizhan.domain.Student"> <property name="id" value="2"/> <property name="name" value="尚学堂123"/> <property name="address" value="北京456"/> </bean>
|
注入Properties对象
<bean id="studentService" class="com.itbaizhan.service.StudentService"> <property name="properties"> <props> <prop key="配置1">值1</prop> <prop key="配置2">值2</prop> </props> </property> </bean>
|
注解实现IOC_准备工作
注解配置和xml配置对于Spring的IOC要实现的功能都是一样的,只是配置的形式不一样。
准备工作
- 创建一个新的Spring项目。
- 编写pojo,dao,service类。
- 编写空的配置文件,如果想让该文件支持注解,需要添加新的约束:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> </beans>
|
注解实现IOC_@Component
作用:用于创建对象,放入Spring容器,相当于<bean id="" class="">
位置:类上方
注意:
要在配置文件中配置扫描的包,扫描到该注解才能生效。
<context:component-scan base-package="com.itbaizhan"></context:component-scan>
|
@Component
注解配置bean的默认id是首字母小写的类名。也可以手动设置bean的id值
@Component public class StudentDaoImpl implements StudentDao{ public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
@Component("studentDao") public class StudentDaoImpl implements StudentDao{ public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
@Component("studentService") public class StudentService { private StudentDao studentDao; public Student findStudentById(int id) { return studentDao.findById(id); } }
|
在spring中,@Component注解中的value属性值表示:bean对象的id
注解实现IOC_@Repository、@Service、@Controller
作用:这三个注解和@Component的作用一样,使用它们是为了区分该类属于什么层。
位置:
- @Repository用于Dao层
- @Service用于Service层
- @Controller用于Controller层
@Repository public class StudentDaoImpl implements StudentDao{}
@Service public class StudentService {}
|
注解实现IOC_@Scope
作用:指定bean的创建策略
位置:类上方
取值范围:singleton prototype request session globalsession
@Service @Scope("singleton") public class StudentService {}
|
注解实现IOC_@Autowired
作用:从容器中查找符合属性类型的对象自动注入属性中。用于代替<bean>
中的依赖注入配置。
位置:属性上方、setter方法上方、构造方法上方。
注意:
@Autowired
写在属性上方进行依赖注入时,可以省略setter方法。
@Component public class StudentService { @Autowired private StudentDao studentDao; public Student findStudentById(int id){ return studentDao.findById(id); } }
@Test public void t2(){ ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); StudentService studentService = (StudentService) ac.getBean("studentService"); System.out.println(studentService.findStudentById(1)); }
|
容器中没有对应类型的对象会报错
public class StudentDaoImpl implements StudentDao{ public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
|
容器中如果有多个对象匹配类型时,会找beanId等于属性名的对象,找不到会报错
@Component("studentDao") public class StudentDaoImpl implements StudentDao{ public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
@Component
public class StudentDaoImpl implements StudentDao{
public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
|
在spring中,@Autowired不能写在上方
注解实现IOC_@Qualifier
作用:在按照类型注入对象的基础上,再按照bean的id注入。
位置:属性上方
注意:@Qualifier必须和@Autowired一起使用。
在容器中如果有多个对象匹配类型时的况下,自主选择注入哪个beanId。而不是根据benId等于属性名的对象这种方法匹配
@Component("studentDao") public class StudentDaoImpl implements StudentDao{ public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
@Component
public class StudentDaoImpl implements StudentDao{
public Student findById(int id) { return new Student(1,"百战程序员","北京"); } }
@Component public class StudentService { @Autowired @Qualifier("studentDaoImpl2") private StudentDao studentDao; public Student findStudentById(int id){ return studentDao.findById(id); } }
|
注解实现IOC_@Value
作用:注入String类型和基本数据类型的属性值。
位置:属性上方
用法:
1.直接设置注入固定的属性值
@Service
public class StudentService { @Value("1") private int count; @Value("hello") private String str; }
|
2.获取配置文件中的属性值:
1.编写配置文件db.properties
jdbc.username=root jdbc.password=123456
|
2.spring核心配置文件扫描配置文件
<context:property-placeholder location="db.properties"></context:property-placeholder>
|
3.注入配置文件中的属性值
@Value("${jdbc.username}") private String username;
@Value("${jdbc.password}") private String password;
|
注解实现IOC_@Configuration
此时基于注解的IOC配置已经完成,但是我们依然离不开Spring的xml配置文件。接下来我们脱离bean.xml,使用纯注解实现IOC。
在真实开发中,我们一般还是会保留xml配置文件,很多情况下使用配置文件更加方便。
纯注解实现IOC需要一个Java类代替xml文件。这个Java类上方需要添加@Configuration,表示该类是一个配置类,作用是代替配置文件。
package com.itbaizhan;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;
@Configuration @ComponentScan("com.itbaizhan") public class SpringConfig { }
|
注解实现IOC_@ComponentScan
作用:指定spring在初始化容器时扫描的包。
位置:配置类上方
package com.itbaizhan;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;
@Configuration @ComponentScan("com.itbaizhan") public class SpringConfig { }
|
注解实现IOC_@PropertySource
作用:代替配置文件中的<context:property-placeholder>
扫描配置文件
位置:配置类上方
注意:配置文件位置前要加关键字classpath
package com.itbaizhan;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource;
@Configuration @ComponentScan("com.itbaizhan") @PropertySource("classpath:db.properties") public class SpringConfig { }
|
jdbc.username = root jdbc.password = root
|
@Test public void t3() { ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class); StudentService studentService = (StudentService) ac.getBean("studentService"); StudentDao studentDao = (StudentDao) ac.getBean("studentDao"); System.out.println(studentService); System.out.println(studentDao); }
|
注解实现IOC_@Bean
作用:将方法的返回值对象放入Spring容器中,如果想将第三方类的对象放入容器,可以使用@Bean
位置:配置类的方法上方。
属性:name:给bean对象设置id
注意:@Bean修饰的方法如果有参数,spring会根据参数类型从容器中查找可用对象。
举例:如果想将jdbc连接对象放入Spring容器,我们无法修改Connection源码添加@Component,此时就需要使用将@Bean该对象放入Spring容器
1.添加驱动依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency>
|
2.将Connection对象放入Spring容器中
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
@Configuration @ComponentScan("com.itbaizhan") @PropertySource("classpath:db.properties")
public class SpringConfig { @Bean(name = "connection") public Connection getConnection(StudentService studentService) { System.out.println(studentService); try { Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection("jdbc:mysql:///mybatis","root","root"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return null; } }
|
3.测试
@Test public void t5(){ ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class); Connection connection = (Connection) ac.getBean("connection"); System.out.println(connection); }
|
注解实现IOC_@Import
作用:如果配置过多,会有多个配置类,该注解可以为主配置类导入其他配置类
位置:主配置类上方
package com.itbaizhan;
import com.itbaizhan.service.StudentService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
@Configuration public class JdbcConfig { @Bean(name = "connection") public Connection getConnection(StudentService studentService) { System.out.println(studentService); try { Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection("jdbc:mysql:///mybatis","root","root"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return null; } }
|
package com.itbaizhan;
import com.itbaizhan.service.StudentService; import org.springframework.context.annotation.*;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
@Configuration @ComponentScan("com.itbaizhan") @PropertySource("classpath:db.properties") @Import(JdbcConfig.class)
public class SpringConfig {
}
|
Spring整合MyBatis_搭建环境
我们知道使用MyBatis时需要写大量创建SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession等对象的代码,而Spring的作用是帮助我们创建和管理对象,所以我们可以使用Spring整合MyBatis,简化MyBatis开发。
创建maven项目,引入依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.itbaizhan</groupId> <artifactId>spring_mybatis</artifactId> <version>1.0-SNAPSHOT</version>
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.28</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.13</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.3.13</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.13</version> </dependency>
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> </dependencies>
</project>
|
Spring整合MyBaits_编写配置文件
1.编写数据库配置文件db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///student3 jdbc.username=root jdbc.password=root
|
2.创建MyBatis配置文件SqlMapConfig.xml,数据源、扫描接口都交由Spring管理,不需要在MyBatis配置文件中设置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
|
3.创建Spring配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.itbaizhan"></context:component-scan>
<context:property-placeholder location="db.properties"></context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="SqlMapConfig.xml"></property> </bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> </bean> </beans>
|
Spring整合MyBatis_准备数据库和实体类
准备数据库
CREATE DATABASE `student`; USE `student`; DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `sex` varchar(10) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; insert into `student`(`id`,`name`,`sex`,`address`) values (1,'百战程序员','男','北京'),(2,'北京尚学堂','女','北京');
|
准备实体类
package com.itbaizhan.domain;
public class Student { private int id; private String name; private String sex; private String address;
public Student() { }
public Student(int id, String name, String sex, String address) { this.id = id; this.name = name; this.sex = sex; this.address = address; }
@Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getSex() { return sex; }
public void setSex(String sex) { this.sex = sex; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; } }
|
Spring整合MyBatis_编写持久层接口和service类
编写持久层接口
package com.itbaizhan.dao;
import com.itbaizhan.domain.Student; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository;
import java.util.List;
@Repository public interface StudentDao { @Select("select * from student3") List<Student> findAll();
@Insert("insert into student values(null,#{name},#{sex},#{address})") void add(Student student); }
|
编写service类
package com.itbaizhan.service;
import com.itbaizhan.dao.StudentDao; import com.itbaizhan.domain.Student; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
import java.util.List;
@Service public class StudentService { @Autowired private SqlSessionTemplate sqlSession;
public List<Student> findAllStudent() { StudentDao studentDao = sqlSession.getMapper(StudentDao.class); return studentDao.findAll(); } }
|
Spring整合MyBatis_Spring整合Junit进行单元测试
1.引入Junit和Spring整合Junit依赖
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.13</version> </dependency>
|
2.编写测试类
package com.itbaizhan.service;
import com.itbaizhan.domain.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml") public class StudentServiceTest { @Autowired private StudentService studentService;
@Test public void testFindAll() { List<Student> allStudent = studentService.findAllStudent(); for (Student student : allStudent) { System.out.println(student.toString()); } } }
|
注意:
使用SqlSessionTemplate创建代理对象还是需要注册接口或者映射文件的。
1.在MyBatis配置文件注册接口
<configuration> <mappers> <mapper class="com.itbaizhan.dao.StudentDao"></mapper> </mappers> </configuration>
|
2.创建sqlSessionFactory时指定MyBatis配置文件
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:SqlMapConfig.xml"></property> </bean>
|
Spring整合MyBatis_自动创建代理对象(不需要手动通过sqlsession和反射创建代理对象)
Spring提供了MapperScannerConfigurer对象,该对象可以自动扫描包创建代理对象,并将代理对象放入容器中,此时不需要使用SqlSession手动创建代理对象。
1.在applicationContext.xml中创建MapperScannerConfigurer对象
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itbaizhan.dao"></property> </bean>
|
2.Service类直接使用代理对象即可
package com.itbaizhan.service;
import com.itbaizhan.dao.StudentDao; import com.itbaizhan.domain.Student; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
import java.util.List;
@Service public class StudentService {
@Autowired private StudentDao studentDao; public List<Student> findAllStudent() { return studentDao.findAll(); }
public void addStudent(Student student) { studentDao.add(student); }
}
|
3.测试
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext.xml") public class StudentServiceTest {
@Autowired private StudentService studentService;
@Test public void testAdd(){ Student student = new Student(0, "百战2", "男", "上海"); studentService.addStudent(student); } }
|
SpringAOP_AOP入门
AspectJ是一个基于Java语言的AOP框架,在Spring框架中建议使用AspectJ实现AOP。
接下来我们写一个AOP入门案例:dao层的每个方法结束后都可以打印一条日志:
引入依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.itbaizhan</groupId> <artifactId>spring_aop</artifactId> <version>1.0-SNAPSHOT</version>
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.13</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> </project>
|
2.编写连接点
package com.itbaizhan.dao;
import org.springframework.stereotype.Repository;
@Repository public class UserDao { public void add(){ System.out.println("用户新增"); } public void delete(){ System.out.println("用户删除"); } public void update(){ System.out.println("用户修改"); } }
|
3.编写通知类
package com.itbaizhan.advice;
public class MyAspectJAdvice { public void myAfterReturning() { System.out.println("打印日志....."); } }
|
4.配置切面
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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"> <context:component-scan base-package="com.itbaizhan"></context:component-scan>
<bean id="myAspectJAdvice" class="com.itbaizhan.advice.MyAspectJAdvice"></bean>
<aop:config> <aop:aspect ref="myAspectJAdvice"> <aop:pointcut id="myPointcut" expression="execution(* com.itbaizhan.dao.UserDao.*(..))"/> <aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut"/> </aop:aspect> </aop:config> </beans>
|
5.测试
package com.itbaizhan.dao;
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserDaoTest { @Test public void testAdd() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao) ac.getBean("userDao"); userDao.add(); }
@Test public void testDelete() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao) ac.getBean("userDao"); userDao.delete(); }
@Test public void testUpdate() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao) ac.getBean("userDao"); userDao.update(); }
}
|
SpringAOP_通知类型
AOP有以下五种常用的通知类型:
通知类型 |
描述 |
前置通知 |
在方法执行前添加功能 |
后置通知 |
在方法正常执行后同添加功能 |
异常通知 |
在方法抛出异常后添加功能 |
最终通知 |
无论方法是否抛出异常,都会执行该通知 |
环绕通知 |
在方法执行前后添加功能 |
1.编写通知方法
package com.itbaizhan.advice;
import jdk.swing.interop.SwingInterOpUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import java.sql.SQLOutput;
public class MyAspectJAdvice { public void myAfterReturning(JoinPoint joinPoint) { System.out.println("切点方法名:"+joinPoint.getSignature().getName()); System.out.println("目标对象:"+joinPoint.getTarget()); System.out.println("打印日志"+joinPoint.getSignature().getName()+"方法被执行了"); }
public void myBefore() { System.out.println("前置通知..."); }
public void myAfterThrowing(Exception ex) { System.out.println("异常通知..."); System.err.println(ex.getMessage()); }
public void myAfter(){ System.out.println("最终通知"); }
public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("环绕前"); Object obj = proceedingJoinPoint.proceed(); System.out.println("环绕后"); return obj; } }
|
2.配置切面
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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"> <context:component-scan base-package="com.itbaizhan"></context:component-scan>
<bean id="myAspectJAdvice" class="com.itbaizhan.advice.MyAspectJAdvice"></bean>
<aop:config> <aop:aspect ref="myAspectJAdvice"> <aop:pointcut id="myPointcut" expression="execution(* com.itbaizhan.dao.UserDao.*(..))"/> <aop:before method="myBefore" pointcut-ref="myPointcut"></aop:before> <aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut"/> <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointcut" throwing="ex"></aop:after-throwing> <aop:after method="myAfter" pointcut-ref="myPointcut"></aop:after> <aop:around method="myAround" pointcut-ref="myPointcut"></aop:around> </aop:aspect> </aop:config> </beans>
|
SpringAOP_切点表达式
使用AspectJ需要使用切点表达式配置切点位置,写法如下:
SpringAOP_多切面框架
我们可以为切点配置多个通知,形成多切面,比如希望dao层的每个方法结束后都可以打印日志并发送邮件:
1.编写发送邮件的通知:
package com.itbaizhan.advice;
import org.aspectj.lang.JoinPoint;
public class MyAspectJAdvice2 { public void myAfterReturning(JoinPoint joinPoint) { System.out.println("发送邮件"); } }
|
2.配置切面
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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"> <context:component-scan base-package="com.itbaizhan"></context:component-scan>
<bean id="myAspectJAdvice" class="com.itbaizhan.advice.MyAspectJAdvice"></bean> <bean id="myAspectJAdvice2" class="com.itbaizhan.advice.MyAspectJAdvice2"></bean>
<aop:config> <aop:aspect ref="myAspectJAdvice"> <aop:pointcut id="myPointcut" expression="execution(public * com.itbaizhan.dao.UserDao.*(..))"/> <aop:before method="myBefore" pointcut-ref="myPointcut"></aop:before> <aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut"/> <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointcut" throwing="ex"></aop:after-throwing> <aop:after method="myAfter" pointcut-ref="myPointcut"></aop:after> <aop:around method="myAround" pointcut-ref="myPointcut"></aop:around> </aop:aspect> <aop:aspect ref="myAspectJAdvice2"> <aop:pointcut id="myPointcut2" expression="execution(public * com.itbaizhan.dao.UserDao.*(..))"/> <aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut2"></aop:after-returning> </aop:aspect> </aop:config> </beans>
|
SpringAOP_注解配置AOP
Spring可以使用注解代替配置文件配置切面:
1.在xml中开启AOP注解支持
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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"> <context:component-scan base-package="com.itbaizhan"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
|
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
|
2.在通知类上方加入注解@Aspect
3.在通知方法上方加入注解`@Before/@AfterReturning/@AfterThrowing/@After/@Around
package com.itbaizhan.advice;
import jdk.swing.interop.SwingInterOpUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component;
import java.sql.SQLOutput; @Aspect @Component public class MyAspectJAdvice { @AfterReturning("execution(* com.itbaizhan.dao.UserDao.*(..))") public void myAfterReturning(JoinPoint joinPoint) { System.out.println("切点方法名:"+joinPoint.getSignature().getName()); System.out.println("目标对象:"+joinPoint.getTarget()); System.out.println("打印日志"+joinPoint.getSignature().getName()+"方法被执行了"); }
@Before("execution(* com.itbaizhan.dao.UserDao.*(..))") public void myBefore() { System.out.println("前置通知..."); }
@AfterThrowing(value = "execution(* com.itbaizhan.dao.UserDao.*(..))",throwing = "ex") public void myAfterThrowing(Exception ex) { System.out.println("异常通知..."); System.err.println(ex.getMessage()); }
@After("execution(* com.itbaizhan.dao.UserDao.*(..))") public void myAfter(){ System.out.println("最终通知"); }
@Around("execution(* com.itbaizhan.dao.UserDao.*(..))") public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("环绕前"); Object obj = proceedingJoinPoint.proceed(); System.out.println("环绕后"); return obj; } }
|
4.测试
@Test
public void testAdd2(){ ApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml"); UserDao userDao = (UserDao) ac.getBean("userDao"); userDao.update(); }
|
如何为一个类下的所有方法统一配置切点:
1.在通知类中添加方法配置切点
@Pointcut("execution(* com.itbaizhan.dao.UserDao.*(..))") public void pointCut(){}
|
2.在通知方法上使用定义好的切点
@Before("pointCut()") public void myBefore(JoinPoint joinPoint) { System.out.println("前置通知..."); }
@AfterReturning("pointCut()") public void myAfterReturning(JoinPoint joinPoint) { System.out.println("后置通知..."); }
|
配置类如何代替xml中AOP注解支持?
在配置类上方添加@EnableAspectJAutoProxy即可
@Configuration @ComponentScan("com.itbaizhan") @EnableAspectJAutoProxy public class SpringConfig {
}
|
SpringAOP_原生Spring实现AOP
除了AspectJ,Spring支持原生方式实现AOP。
1.引入依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.13</version> </dependency>
|
2.编写通知类
public class SpringAop implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice, MethodInterceptor {
@Override public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("前置通知"); }
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("后置通知"); }
@Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("环绕前"); Object proceed = invocation.proceed(); System.out.println("环绕后"); return proceed; }
public void afterThrowing(Exception ex){ System.out.println("发生异常了!"); } }
|
Spring原生方式实现AOP时,只支持四种通知类型:
通知类型 |
实现接口 |
前置通知 |
MethodBeforeAdvice |
后置通知 |
AfterReturningAdvice |
异常通知 |
ThrowsAdvice |
环绕通知 |
MethodInterceptor |
3.编写配置类
<bean id="springAop" class="com.itbaizhan.advice.SpringAop"></bean>
<bean id="userDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="userDao"></property> <property name="interceptorNames"> <list> <value>springAop</value> </list> </property> <property name="proxyTargetClass" value="true"></property> </bean>
|
4.编写测试类
public class UserDaoTest2 {
@Test public void testAdd(){ ApplicationContext ac = new ClassPathXmlApplicationContext("bean2.xml"); UserDao userDao = (UserDao) ac.getBean("userDaoProxy"); userDao.update(); } }
|
SpringAOP_SchemaBased实现AOP
SchemaBased(基础模式)配置方式是指使用Spring原生方式定义通知,而使用AspectJ框架配置切面。
1.编写通知类
public class SpringAop implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice, MethodInterceptor {
@Override public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("前置通知"); }
@Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("后置通知"); }
@Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("环绕前"); Object proceed = invocation.proceed(); System.out.println("环绕后") return proceed; }
public void afterThrowing(Exception ex){ System.out.println("发生异常了!"); } }
|
2.配置切面
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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"> <context:component-scan base-package="com.itbaizhan"></context:component-scan>
<!-- 通知对象 --> <bean id="springAop2" class="com.itbaizhan.advice.SpringAop2"></bean> <!-- 配置切面 --> <aop:config> <!-- 配置切点 --> <aop:pointcut id="myPointcut" expression="execution(* com.itbaizhan.dao.UserDao.*(..))"/> <!-- 配置切面:advice-ref:通知对象 pointcut-ref:切点 --> <aop:advisor advice-ref="springAop2" pointcut-ref="myPointcut"></aop:advisor> </aop:config> </beans>
|
3.测试
@Test public void t6(){ ApplicationContext ac = new ClassPathXmlApplicationContext("aop3.xml"); UserDao userDao = (UserDao) ac.getBean("userDao"); userDao.add(); }
|
SchemaBased(基础模式)配置AOP是指使用Spring原生方式定义通知,使用AspectJ框架配置切面
Spring事务_事务简介
事务:不可分割的原子操作,即一系列的操作要么同时成功,要么同时失败。
开发过程中,事务管理一般在service层,service层中可能会操作多次数据库,这些操作是不可分割的,否则当程序报错时,可能会造成数据异常。
如:张三给李四转账时,需要两次操作数据库:张三存款减少、李四存款增加。如果这两次数据库操作间出现异常,则会造成数据错误。
1.准备数据库
CREATE DATABASE `spring` ; USE `spring`; DROP TABLE IF EXISTS `account`; CREATE TABLE `account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) DEFAULT NULL, `balance` double DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; insert into `account`(`id`,`username`,`balance`) values (1,'张三',1000),(2,'李四',1000);
|
2.创建maven项目,引入依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.itbaizhan</groupId> <artifactId>spring_transfer</artifactId> <version>1.0-SNAPSHOT</version>
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.13</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.3.13</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.13</version> </dependency>
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency>
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.13</version> <scope>test</scope> </dependency> </dependencies>
</project>
|
3.创建配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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">
<context:component-scan base-package="com.itbaizhan"></context:component-scan>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> </bean>
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itbaizhan.dao"></property> </bean> </beans>
|
4.编写JAVA代码
package com.itbaizhan.domain;
public class Account { private int id; private String username; private double balance;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public double getBalance() { return balance; }
public void setBalance(double balance) { this.balance = balance; }
@Override public String toString() { return "Account{" + "id=" + id + ", username='" + username + '\'' + ", balance=" + balance + '}'; }
public Account() { }
public Account(int id, String username, double balance) { this.id = id; this.username = username; this.balance = balance; } }
|
package com.itbaizhan.dao;
import com.itbaizhan.domain.Account; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository;
@Repository public interface AccountDao { @Select("select * from account where id = #{id}") Account findById(int id);
@Update("update account set balance = #{balance} where id = #{id}") void update(Account account); }
|
package com.itbaizhan.service;
import com.itbaizhan.dao.AccountDao; import com.itbaizhan.domain.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
@Service public class AccountService { @Autowired private AccountDao accountDao;
public void transfer(int id1,int id2,double price) { // 转出人减少余额 Account account1 = accountDao.findById(id1); account1.setBalance(account1.getBalance()-price); accountDao.update(account1); int i = 1/0;//模拟程序出错
//转入人增加余额 Account account2 = accountDao.findById(id2); account2.setBalance(account2.getBalance()+price); accountDao.update(account2); }}
|
5.测试转账
package com.itbaizhan.service;
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:ApplicationContext.xml") public class AccountServiceTest { @Autowired private AccountService accountService;
@Test public void testTransfer() { accountService.transfer(1,2,300); } }
|
此时没有事务管理,会造成张三的余额减少,而李四的余额并没有增加。所以事务处理位于业务层,即一个service方法是不能分割的。
Spring事务_Spring事务管理方案
在service层手动添加事务可以解决该问题:
@Autowired private SqlSessionTemplate sqlSession;
public void transfer(int id1, int id2, double price) { try{ Account account1 = accountDao.findById(id1); account1.setBalance(account1.getBalance()-price); accountDao.update(account1); int i = 1/0;
Account account2 = accountDao.findById(id2); account2.setBalance(account2.getBalance()+price); accountDao.update(account2); sqlSession.commit(); }catch(Exception ex){ sqlSession.rollback(); } }
|
在Spring管理下不允许手动提交和回滚事务。此时我们需要使用Spring的事务管理方案,在Spring框架中提供了两种事务管理方案:
- 编程式事务:通过编写代码实现事务管理。
- 声明式事务:基于AOP技术实现事务管理。
在Spring框架中,编程式事务管理很少使用,我们对声明式事务管理进行学习
Spring的声明式事务管理在底层采用了AOP技术,其最大的优点在于无需通过编程的方式管理事务,只需要在配置文件中进行相关的规则声明,就可以将事务规则应用到业务逻辑中。
使用AOP技术为·Service方法添加如下通知:
Spring事务_Spring事务管理器
Spring依赖事务管理器进行事务管理,事务管理器即一个通知类,我们为该通知类设置切点为service层方法即可完成事务自动管理。
由于不同技术操作数据库,进行事务操作的方法不同。如:JDBC提交事务是connection.commit()
,MyBatis提交事务是sqlSession.commit()
,所以Spring提供了多个事务管理器。
事务管理器名称 |
作用 |
org.springframework.jdbc.datasource.DataSourceTransactionManager |
针对JDBC技术提供的事务管理器。适用于JDBC和MyBatis。 |
org.springframework.orm.hibernate3.HibernateTransactionManager |
针对于Hibernate框架提供的事务管理器。适用于Hibernate框架。 |
org.springframework.orm.jpa.JpaTransactionManager |
针对于JPA技术提供的事务管理器。适用于JPA技术。 |
org.springframework.transaction.jta.JtaTransactionManager |
跨越了多个事务管理源。适用在两个或者是多个不同的数据源中实现事务控制。 |
我们使用MyBatis操作数据库,接下来使用DataSourceTransactionManager
进行事务管理。
1.引入依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.3.13</version> </dependency>
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency>
|
2.在配置文件中引入约束
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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
|
3.进行事务配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.itbaizhan"></context:component-scan>
<!-- 创建druid数据源对象 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> </bean>
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itbaizhan.dao"></property> </bean>
<!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
<!-- 进行事务相关配置 --> <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice>
<!-- 配置切面 --> <aop:config> <!-- 配置切点 --> <aop:pointcut id="pointcut" expression="execution(* com.itbaizhan.service.*.*(..))"/> <!-- 配置通知 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor> </aop:config> </beans>
|
Spring事务_事务控制的API
Spring进行事务控制的功能是由三个接口提供的,这三个接口是Spring实现的,在开发中我们很少使用到,只需要了解他们的作用即可:
PlatformTransactionManager是Spring提供的事务管理器接口,所有事务管理器都实现了该接口。该接口中提供了三个实务操作方法:
- TransactionStatus getTransaction(TransactionDefinition definition):获取事务状态信息。
- void commit(TransactionStatus status):事务提交
- void rollback(TransactionStatus status):事务回滚
TransactionDefinition接口
TransactionDefinition是事务的定义信息对象,它有如下方法;
- String getName():获取事务对象名称。
- int getIsolationLevel():获取事务的隔离级别。
- int getPropagationBehavior():获取事务的传播行为。
- int getTimeout():获取事务的超时时间。
- boolean isReadOnly():获取事务是否只读。
TransactionStatus接口
TransactionStatus是事务的状态接口,它描述了某一时间点上事务的状态信息。它有如下方法:
- void flush() 刷新事务
- boolean hasSavepoint() 获取是否存在保存点
- boolean isCompleted() 获取事务是否完成
- boolean isNewTransaction() 获取是否是新事务
- boolean isRollbackOnly() 获取是否回滚
- void setRollbackOnly() 设置事务回滚
Spring事务_事务的相关配置
在<tx:advice>
中可以进行事务的相关配置
<tx:advice id="txAdvice"> <tx:attributes> <tx:method name="*"/> <tx:method name="find*" read-only="true"/> </tx:attributes> </tx:advice>
|
tx:method 中的属性:
name:指定配置的方法。表示所有方法,find表示所有以find开头的方法。
read-only:是否是只读事务,只读事务不存在数据的修改,数据库将会为只读事务提供一些优化手段,会对性能有一定提升,建议在查询中开启只读事务。
timeout:指定超时时间,在限定的时间内不能完成所有操作就会抛异常。默认永不超时
rollback-for:指定某个异常事务回滚,其他异常不回滚。默认所有异常回滚。
no-rollback-for:指定某个异常不回滚,其他异常回滚。默认所有异常回滚。
propagation:事务的传播行为
isolation:事务的隔离级别
Spring事务_事务的传播行为
事务传播行为是指多个含有事务的方法相互调用时,事务如何在这些方法间传播。
如果在service层的方法中调用了其他的service方法,假设每次执行service方法都要开启事务,此时就无法保证外层方法和内层方法处于同一个事务当中。
public void method1(){ method2(); System.out.println("method1"); }
public void method2(){ System.out.println("method2"); }
|
事务的传播特性就是解决这个问题的,Spring帮助我们将外层方法和内层方法放入同一事务中。
传播行为 |
介绍 |
REQUIRED |
默认。支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。 |
SUPPORTS |
支持当前事务,如果当前没有事务,就以非事务方式执行。 |
MANDATORY |
支持当前事务,如果当前没有事务,就抛出异常。 |
REQUIRES_NEW |
新建事务,如果当前存在事务,把当前事务挂起。 |
NOT_SUPPORTED |
以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。 |
NEVER |
以非事务方式执行,如果当前存在事务,则抛出异常。 |
NESTED |
必须在事务状态下执行,如果没有事务则新建事务,如果当前有事务则创建一个嵌套事务 |
Spring事务_事务的隔离级别
事务隔离级别反映事务提交并访问时的处理态度
隔离级别越高,数据出问题的可能性越低,但效率也会越低
隔离级别 |
脏读 |
不可重复读 |
幻读 |
READ_UNCOMMITED(读取未提交内容) |
Yes |
Yes |
Yes |
READ_COMMITED(读取提交内容) |
No |
Yes |
Yes |
REPEATABLE_READ(重复读) |
No |
No |
Yes |
SERIALIZABLE(可串行化) |
No |
No |
No |
如果设置为DEFAULT会使用数据库的隔离级别
- SqlServer , Oracle默认的事务隔离级别是READ_COMMITED
- Mysql的默认隔离级别是REPEATABLE_READ
Spring事务_注解配置声明式事务
Spring支持使用注解配置声明式事务。用法如下:
1.注册事务注解驱动
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.itbaizhan"></context:component-scan>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> </bean>
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itbaizhan.dao"></property> </bean>
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
</beans>
|
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
|
2.在需要事务支持的方法或类上加@Transactional
package com.itbaizhan.service;
import com.itbaizhan.dao.AccountDao; import com.itbaizhan.domain.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT ) public class AccountService { @Autowired private AccountDao accountDao;
public void transfer(int id1,int id2,double price) { Account account1 = accountDao.findById(id1); account1.setBalance(account1.getBalance()-price); accountDao.update(account1);
Account account2 = accountDao.findById(id2); account2.setBalance(account2.getBalance()+price); accountDao.update(account2); }
@Transactional(isolation = Isolation.READ_UNCOMMITTED,readOnly = true) public Account findById(int id) { return accountDao.findById(id); } }
|
3.配置类代替xml中的注解事务支持:在配置类上方写@Enable TranscationManagement
package com.itbaizhan;
import com.alibaba.druid.pool.DruidDataSource; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration @ComponentScan("com.itbaizhan") @EnableTransactionManagement public class SpringConfig { @Bean public DataSource getDataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName("com.mysql.jdbc.Driver"); druidDataSource.setUrl("jdbc:mysql:///spring"); druidDataSource.setUsername("root"); druidDataSource.setPassword("root"); return druidDataSource; }
@Bean public SqlSessionFactoryBean getSqlSession(DataSource dataSource){ SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); return sqlSessionFactoryBean; }
@Bean public DataSourceTransactionManager getTransactionManager(DataSource dataSource){ DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(dataSource); return dataSourceTransactionManager; } }
|