Spring介绍
什么是Spring
Spring是一个开源框架,为简化企业级开发而生。它以IOC(控制反转)和AOP(面向切面)为思想内核,提供了控制层SpringMVC、数据层SpringData、服务层事务管理等众多技术,并可以整合众多第三方框架。
Spring将很多复杂的代码变得优雅简洁,有效的降低代码的耦合
度,极大的方便项目的后期维护、升级和扩展。
Spring官网地址:https://spring.io/
Spring6版本介绍
2022年底,Spring正式发布Spring6,此时距离Spring5发布已经有
四年多了。Spring6是一个跨越式的升级:
- 整个框架支持的最低JDK版本直接跨越到 JDK17
- Servlet、JPA 等从javax迁移到jakarta命名空间。
- 兼容jakarta EE 9 、jakarta EE 10。
- 支持AOT技术。
Spring本次升级更多是为了SpringBoot升级到3.0做准备,我们也将
在SpringBoot3.0中详细讲解AOT等新版的功能。
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 {//根据id查询学生Student findById(int id);
}public class StudentDaoImpl implements StudentDao {@Overridepublic Student findById(int id) {//模拟从数据库查找出学生return new Student(9,"雷军",20,"男",2);}
}public class StudentService {public Student findStudentById(int id){//此处就是调用者在创建对象StudentDao studentDao=new StudentDaoImpl();return studentDao.findById(21);}
}
这种写法有两个缺点:
- 浪费资源:StudentService调用方法时即会创建一个对象,如果不断调用方法则会创建大量StudentDao对象。
- 代码耦合度高:假设随着开发,我们创建了StudentDao另一个更加完善的实现类StudentDaoImpl2,如果在StudentService中想使用StudentDaoImpl2,则必须修改源码。
而IOC思想是将创建对象的权利交给框架,框架会帮助我们创建对象,分配对象的使用,控制权由程序代码转移到了框架中,控制权发生了反转,这就是Spring的IOC思想。而IOC思想可以完美的解决以上两个问题。
IOC_自定义对象容器
创建一个集合容器,先将对象创建出来放到容器中,需要使用对象时,只需要从容器中获取对象即可,而不需要重新创建,此时容器就是对象的管理者。
- 创建实体类
public class Student {private int id;private String name;private String address;}
- 创建Dao接口和实现类
public interface StudentDao {//根据id查询学生Student findById(int id);
}public class StudentDaoImpl implements StudentDao {@Overridepublic Student findById(int id) {//模拟从数据库查找出学生return new Student(9,"雷军","北京");}
}public class StudentDaoImpl1 implements StudentDao {@Overridepublic Student findById(int id) {System.out.println("IOC");return new Student(9,"雷军","北京");}
}
3.创建配置文件bean.properties,该文件中定义管理的对象
studentDao=com.spring.dao.impl.StudentDaoImpl
4.创建容器管理类,该类在类加载时读取配置文件,将配置文件中配置的对象全部创建并放入容器中。
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);} catch (IOException e) {throw new RuntimeException(e);}//遍历配置文件的所有配置信息Enumeration<Object> keys = properties.keys();while (keys.hasMoreElements()) {String key = keys.nextElement().toString();String value = properties.getProperty(key);try {//创建对象,将对象放入集合Object o = Class.forName(value).newInstance();map.put(key, o);} catch (Exception e) {e.printStackTrace();}}}//从容器中获取对象public static Object getBean(String key){return map.get(key);}}
- 创建Dao对象的调用者StudentService
public class StudentService {public Student findStudentById(int id){StudentDao studentDao1=(StudentDao) Container.getBean("studentDao");System.out.println(studentDao1.hashCode());return studentDao1.findById(id);}
}
- 测试StudentService
public class Test {public static void main(String[] args) {StudentService service=new StudentService();System.out.println(service.findStudentById(9));}
}
测试结果:
- StudentService从容器中每次拿到的都是同一个StudentDao对象,节约了资源。
- 如果想使用StudentDaoImpl2对象,只需要修改bean.properties的内容为
studentDao=com.itbaizhan.dao.StudentDaoImpl2
即可,无需修改Java源码。
IOC_Spring实现IOC
使用Spring实现IOC,Spring内部也有一个容器用来管理对象。
spring更新之后要求17jdk
- 创建Maven工程,引入依赖
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.11</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version><scope>test</scope></dependency></dependencies><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties>
- 创建POJO类、Dao类和接口
public class Student {private int id;private String name;private String address;// 省略getter/setter/构造方法/tostring
}public interface StudentDao {// 根据id查询学生Student findById(int id);
}public class StudentDaoImpl implements StudentDao {@Overridepublic Student findById(int id) {return new Student(1,"熊出没","北京");}
}
- 编写bean.xml配置文件,配置文件中配置需要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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 定义一个简单的bean --><bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl"></bean></beans>
- 测试从Spring容器中获取对象。
public class TestContainer {@Testpublic void t1(){//创建Spring容器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:使用该类不读取配置文件,而是会读取注解
@Testpublic void t2(){//创建spring容器//从项目中读取配置文件ApplicationContext ac1=new ClassPathXmlApplicationContext("bean.xml");//从磁盘中读取配置文件ApplicationContext ac2=new FileSystemXmlApplicationContext("D:\\springdemo1\\src\\main\\resources\\bean.xml");//从容器中获取对象StudentDao userDao=(StudentDao) ac1.getBean("StudentDao");System.out.println(userDao);System.out.println(userDao.findById(1));}
IOC_对象的创建方式
Spring会帮助我们创建bean,那么它底层是调用什么方法进行创建
的呢?
使用构造方法
Spring默认使用类的空参构造方法创建bean:
//假如类没有空参构造方法,将无法完成bean的创建
public class StudentDaoImpl implements StudentDao {public StudentDaoImpl(int a) {}@Overridepublic Student findById(int id) {return new Student(1,"熊出没","北京");}
}
使用工厂类的方法
Spring可以调用工厂类的方法创建bean:
- 创建工厂类,工厂类提供创建对象的方法:
public class StudentDaoFactory {public StudentDao getStudentDao(){return new StudentDaoImpl(1);}
}
- 在配置文件中配置创建bean的方式为工厂方式。
<!-- id:工厂对象的id,class:工厂类--><bean id="StudentDaoFactory" class="com.spring.StudentDaoFactory"></bean>
<!--id:bean对象的id factory-bean:工厂对象的id,factory-method:工厂方法--><bean id="StudentDao" factory-bean="StudentDaoFactory" factory-method="getStudentDao"></bean>
- 测试
@Testpublic void t2(){//创建spring容器//从项目中读取配置文件ApplicationContext ac1=new ClassPathXmlApplicationContext("bean.xml");//从磁盘中读取配置文件ApplicationContext ac2=new FileSystemXmlApplicationContext("D:\\springdemo1\\src\\main\\resources\\bean.xml");//从容器中获取对象StudentDao userDao=(StudentDao) ac1.getBean("StudentDao");System.out.println(userDao);System.out.println(userDao.findById(1));}
使用工厂类的静态方法
Spring可以调用工厂类的静态方法创建bean:
- 创建工厂类,工厂提供创建对象的静态方法。
public class StudentDaoFactory2 {public static StudentDao getStudentDao2(){return new StudentDaoImpl();}
}
- 在配置文件中配置创建bean的方式为工厂静态方法。
<!-- id:bean的id class:工厂全类名 factory-method:工厂静态方法--><bean id="StudentDao" class="com.spring.StudentDaoFactory2"factory-method="getStudentDao2"></bean>
- 测试
@Testpublic void t2(){//创建spring容器//从项目中读取配置文件ApplicationContext ac1=new ClassPathXmlApplicationContext("bean.xml");//从磁盘中读取配置文件ApplicationContext ac2=new FileSystemXmlApplicationContext("D:\\springdemo1\\src\\main\\resources\\bean.xml");//从容器中获取对象StudentDao userDao=(StudentDao) ac1.getBean("StudentDao");System.out.println(userDao);System.out.println(userDao.findById(1));}
IOC_对象的创建策略
Spring通过配置 < bean> 中的 scope 属性设置对象的创建策略,共有五
种创建策略:
singleton:单例,默认策略。整个项目只会创建一个对象,通过 < bean> 中的 lazy-init 属性可以设置单例对象的创建时机:
lazy-init=“false”(默认):立即创建,在容器启动时会创建配置文件中的所有Bean对象。
lazy-init=“true”:延迟创建,第一次使用Bean对象时才会创建。
- 配置单例策略:
<bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl"scope="singleton"lazy-init="true"></bean><bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl"scope="singleton"lazy-init="false"></bean>
- 测试单例策略:
// 为Bean对象的类添加构造方法
public StudentDaoImpl2(){System.out.println("创建
StudentDao!!!");
}@Testpublic void t3(){//创建Spring容器ApplicationContext ac=new ClassPathXmlApplicationContext("bean.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());}
- prototype:多例,每次从容器中获取时都会创建对象。
<bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl"scope="prototype"lazy-init="false"></bean>
- request:每次请求创建一个对象,只在web环境有效
- session:每次会话创建一个对象,只在web环境有效
- gloabal-session:一次集群环境的会话创建一个对象,只在web环境有效。
IOC_对象的销毁时机
对象的创建策略不同,销毁时机也不同:
- singleton:对象随着容器的销毁而销毁。
- prototype:使用JAVA垃圾回收机制销毁对象。
- request:当处理请求结束,bean实例将被销毁。
- session:当HTTP Session最终被废弃的时候,bean也会被销毁掉。
- gloabal-session:集群环境下的session销毁,bean实例也将被销毁。
IOC_bean对象的生命周期(创建–使用–销毁)
Bean对象的生命周期包含创建——使用——销毁,Spring可以配置
Bean对象在创建和销毁时自动执行的方法:
- 定义生命周期方法
public class StudentDaoImpl2 implements StudentDao {//创建时自动执行的方法public void init(){System.out.println("创建StudentDao!!!");}@Overridepublic Student findById(int id) {return null;}//销毁时自动执行的方法public void destory(){System.out.println("销毁StudentDao!!");}
}
- 配置生命周期方法
<bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl2"scope="singleton"init-method="init"destroy-method="destory"></bean>
- 测试
@Testpublic void t4(){//创建Spring容器ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");//销毁spring容器,ClassPathXmlApplicationContext才有销毁容器的方法ac.close();}
IOC_获取对象的方式
Spring有多种获取容器中对象的方式:
通过id/name获取
- 配置文件
<bean name="StudentDao" class="com.spring.dao.impl.StudentDaoImpl2"></bean><bean id="StudentDao" class="com.spring.dao.impl.StudentDaoImpl2"></bean>
- 获取对象
StudentDao studentDao=(StudentDao)ac.getBean("StudentDao");
通用类型获取
- 配置文件
<bean name="StudentDao" class="com.spring.dao.Impl.StudentImpl2">
</bean>
- 获取对象
StudentDao studentDao=ac.getBean(StudentDao.class);
//使用类型没有进行强转
通用类型+id/name获取
虽然使用类型获取不需要强转,但如果在容器中有一个接口的多个实现类对象,则获取时会报错,此时需要使用通用类型+id/name获取
- 配置文件
<bean name="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl1"></bean>
<bean name="StudentDao1" class="com.spring.Dao.Impl.StudentDaoImpl2">
- 获取对象
StudentDao studentDao=ac.getBean("StudentDao",StudentDao.class);
DI(Dependency Injection)_什么是依赖注入
依赖注入(Dependency Injection,简称DI),它是Spring控制反
转思想的具体实现。
控制反转将对象的创建交给了Spring,但是对象中可能会依赖其他对象。比如service类中要有dao类的属性,我们称service依赖于dao。之前需要手动注入属性值,代码如下:
public interface StudentDao {//根据id查询学生Student findById(int id);
}//假如类没有空参构造方法,将无法完成bean的创建
public class StudentDaoImpl implements StudentDao {public StudentDaoImpl(int id) {}public StudentDaoImpl() {System.out.println("创建StudentDao!!");}@Overridepublic Student findById(int id) {return new Student(1,"熊出没","北京");}
}public class StudentService {//service依赖dao,手动注入属性值,即手动维护依赖关系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注入
在之前开发中,我们可以通过setter方法或构造方法设置对象属性
值:
//setter方法设置属性
StudentService studentService=new StudentService();
StudentDao studentDao=new StudentDao();
studentService.setStudentDao(studentDao);//构造方法设置属性
StudentDao studentDao=new StudentDao();
StudentService studentService=new StudentService(studentDao);
Spring可以通过调用setter方法或者构造方法给属性赋值
- 被注入类编写属性的setter方法
public class StudentService {//service依赖dao,手动注入属性值,即手动维护依赖关系private StudentDao studentDao;public void setStudentDao(StudentDao studentDao){this.studentDao=studentDao;}public Student findStudentById(int id){return studentDao.findById(id);}
}
- 配置文件中,给需要注入属性值的 < bean>中设置 < property>
<bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl"></bean><bean id="StudentService" class="com.spring.service.StudentService">
<!-- 依赖注入 name:对象属性名 ref:容器中对象的ID值--><property name="studentDao" ref="StudentDao"></property></bean>
- 测试是否注入成功
@Testpublic void testDI1(){ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");StudentService studentService=ac.getBean(StudentService.class);System.out.println(studentService.findStudentById(1));}
DI_构造方法注入
- 被注入类编写有参的构造方法
public class StudentService {//service依赖dao,手动注入属性值,即手动维护依赖关系private StudentDao studentDao;public StudentService(StudentDao studentDao){this.studentDao=studentDao;}}
- 给需要注入属性值的 < bean>中设置 < constructor-arg>
<bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl"></bean><bean id="StudentService" class="com.spring.service.StudentService"><!-- 依赖注入--><!-- name:对象的属性名 ref:配置文件中注入对象的Id值--><constructor-arg name="studentDao" ref="StudentDao"></constructor-arg></bean>
- 测试是否注入成功
@Testpublic void t5(){ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");StudentService studentService=(StudentService) ac.getBean("StudentService");System.out.println(studentService.findStudentById(1));}
DI_自动注入
自动注入不需要在 < bean>标签中添加其他标签注入属性值,而是自动从容器中找到相应的bean对象设置为属性值。
自动注入有两种配置方式:
- 全局配置:在 < beans>中设置 default-autowire属性可以定义所有bean对象的自动注入策略。
- 局部配置:在 < bean>中设置 autowire属性可以定义当前bean对象的自动注入策略。
autowire的取值如下:
- no:不会进行自动注入。
- default:全局配置default相当于no,局部配置default表示使用全局配置
- byName:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供setter方法。
- byType:在Spring容器中查找类型与属性类型相同的bean,并进行注入。需要提供setter方法。
- constructor:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供构造方法。
测试自动注入:
- 为依赖的对象提供setter和构造方法:
public class StudentService {//service依赖dao,手动注入属性值,即手动维护依赖关系private StudentDao studentDao;//构造方法public StudentService(){}public StudentService(StudentDao studentDao){this.studentDao=studentDao;}//setter方法public void setStudentDao(StudentDao studentDao){this.studentDao=studentDao;}//调用依赖方法public Student findStudentById(int id){return studentDao.findById(id);}
}
- 配置自动注入:
<!-- 根据beanId等于属性名自动注入--><bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl"></bean><bean id="StudentService" class="com.spring.service.StudentService"autowire="byName"></bean>
<!-- 根据bean类型等于属性类型自动注入--><bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl"></bean><bean id="StudentService" class="com.spring.service.StudentService"autowire="byType" ></bean>
<!-- 利用构造方法自动注入--><bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl"></bean>
<bean id="StudentService" class="com.spring.service.StudentService"autowire="constructor"></bean>
<!-- 配置全局自动注入-->
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="constructor">
DI_注入bean类型、简单数据类型
DI支持注入bean类型、基本数据类型和字符串、List集合、Set集合、Map集合、Properties对象类型等,他们的写法如下:
- 准备注入属性的类
public class StudentService2 {private StudentDao studentDao;//bean属性private String name;//字符串类型private int count;//基本数据类型private List<String> names;//字符串类型List集合private List<Student> student1;//对象类型List集合private Set<Student> student2;//对象类型Set集合private Map<String,String> names2;//字符串类型Map集合private Map<String,Student> student3;//对象类型Map集合private Properties properties;//Properties类型// 省略getter/setter/toString}
- 准备测试方法
@Testpublic void t5(){ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");StudentService2 studentService=(StudentService2) ac.getBean("StudentService2");System.out.println(studentService.findStudentById(1));}
注入bean类型
写法一:
<bean id="StudentDao" class="com.spring.dao.StudentDaoImpl">
</bean>
<bean id="StudentService" class="com.spring.service.StudentService2">
<property name="studentDao" ref="studentDao"></property>
</bean>
写法二:
<bean id="StudentDao" class="com.spring.dao.Impl.StudnetDaoImpl">
</bean>
<bean id="StudentService2" class="com.spring.service.StudentService2">
<property name="studentDao">
<ref bean="studentDao"></ref>
</property>
</bean>
注入简单数据类型
简单数据类型包含基本数据类型和字符串,写法如下:
写法一:
name:属性名 value:属性值
<bean id="StudentDao" class="com.spring.dao.Impl.SrudentDaoImpl2">
<property name="name" value="占星魔仙"></property>
</bean>
写法二:
name:属性名 value:属性值
<property name="count">
<value>10</value>
</property>
DI_注入List集合、Set集合
<bean id="StudentDao" class="com.spring.dao.Impl.StudentDaoImpl2"></bean>
<bean id="StudentService2" class="com.spring.service.StudentService2">
<!-- 简单数据类型List集合 name:属性名-->
<property name="names"><list><value>魔仙堡</value><value>占星魔仙</value></list>
</property><!-- 对象类型List集合 name:属性名-->
<property name="student1">
<list><bean class="com.spring.pojo.Student"><property name="id" value="3"></property><property name="name" value="占星魔仙"></property><property name="address" value="魔仙堡"></property></bean><bean class="com.spring.pojo.Student"><propert name="id" value="4"></property><property name="name" value="熊大"></property><property name="address" value="狗熊岭"></property></bean>
</list>
</property>
</bean>
测试方法:
@Testpublic void t5(){ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");StudentService2 studentService=(StudentService2) ac.getBean("StudentService2");System.out.println(studentService.getStudent1());System.out.println(studentService.getNames());}
注入Set集合
<bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl2"></bean>
<bean id="StudentService2" class="com.spring.service.StudentService2">
<!-- Set集合-->
<!-- name表示set名--><property name="student2"><set><bean class="com.spring.pojo.Student"><property name="name" value="熊二"></property><property name="address" value="狗熊岭"></property><property name="id" value="1"></property></bean><bean class="com.spring.pojo.Student"><property name="id" value="1"></property><property name="address" value="狗熊岭"></property><property name="name" value="涂涂"></property></bean></set></property></bean>
测试方法:
@Testpublic void t5(){ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");StudentService2 studentService=(StudentService2) ac.getBean("StudentService2");System.out.println(studentService.getStudent2());}
DI_注入Map集合、Properties对象
注入简单数据类型Map集合
<bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl2"></bean>
<bean id="StudentService2" class="com.spring.service.StudentService2"><property name="names2"><map><entry key="student1" value="熊大"/><entry key="student2" value="熊二"/></map></property>
</bean>
测试方法
@Testpublic void t5(){ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");StudentService2 studentService=(StudentService2) ac.getBean("StudentService2");System.out.println(studentService.getNames2());}
注入对象类型Map集合
<bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl2"></bean>
<bean id="StudentService2" class="com.spring.service.StudentService2"><property name="student3" ><map><entry key="student1" value-ref="s1"></entry><entry key="student2" value-ref="s2"></entry></map></property></bean><bean id="s1" class="com.spring.pojo.Student"><property name="id" value="1"></property><property name="name" value="喜羊羊"/><property name="address" value="青青草原"/></bean><bean id="s2" class="com.spring.pojo.Student"><property name="id" value="2"/><property name="name" value="美羊羊"/><property name="address" value="青青草原"/></bean></beans>
测试方法
@Testpublic void t5(){ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");StudentService2 studentService=(StudentService2) ac.getBean("StudentService2");System.out.println(studentService.getStudent3());}
注入Properties对象
<bean id="StudentDao" class="com.spring.Dao.Impl.StudentDaoImpl2"></bean>
<bean id="StudentService2" class="com.spring.service.StudentService2"><property name="properties"><props><prop key="配置1">值1</prop><prop key="配置2">值2</prop></props></property>
</bean>
测试方法
@Testpublic void t5(){ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");StudentService2 studentService=(StudentService2) ac.getBean("StudentService2");System.out.println(studentService.getProperties());}
注解实现IOC_@Component
注解配置和xml配置对于Spring的IOC要实现的功能都是一样的,只是配置的形式不一样。
- 创建一个新的Spring项目。
- 编写pojo,dao,service类。
- 编写空的配置文件,Spring配置文件需要添加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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"></beans>
- 使用 @Component,将对象放入Spring容器管理。
@Component
作用:用于创建对象,放入Spring容器,相当于 < bean id=“” class=“”>
位置:类上方
- 要在配置文件中配置扫描的包,扫描到该注解才能生效。
<context:component-scan base-package="com.spring"></context:component-scan>
- @Component注解配置bean的默认id是首字母小写的类名。也可以手动设置bean的id值。
@Component
public class StudentDaoImpl2 implements StudentDao {@Overridepublic Student findById(int id) {return new Student(2,"清华大学","北京");}
}
@Component("studentDao")
public class StudentDaoImpl2 implements StudentDao {@Overridepublic Student findById(int id) {return new Student(2,"清华大学","北京");}
}
注解实现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 global-session
@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));}
容器中没有对应类型的对象会报错
// 如果StudentDaoImpl没有放到容器中会报错
//@Component("studentDao")
public class StudentDaoImpl implements StudentDao{ public Student findById(int id) { // 模拟根据id查询学生 return new Student(1,"黑魔仙小月","北京"); }}
容器中有多个对象匹配类型时,会找beanId=属性名的对象,找不到会报错。
// 如果容器中都多个同类型对象,会根据id值等于属性名找对象
@Component("studentDao")
public class StudentDaoImpl implements StudentDao{ public Student findById(int id) { // 模拟根据id查询学生 return new Student(1,"美雪","北京");}}
@Component
public class StudentDaoImpl2 implements StudentDao{ public Student findById(int id) { // 模拟根据id查询学生 return new Student(1,"美雪","北京"); }}
注解实现IOC_@Qualifier
作用:在按照类型注入对象的基础上,再按照bean的id注入。
位置:属性上方
注意:@Qualifier必须和@Autowired一起使用。
@Component
public class StudentService { @Autowired @Qualifier("studentDaoImpl2") private StudentDao studentDao; public Student findStudentById(int id){ return studentDao.findById(id); }}
注解实现IOC_@Value
作用:注入简单数据类型的属性值。
位置:属性上方
用法:
1.直接设置固定的属性值
@Service
public class StudentService { @Value("1") private int count;@Value("hello") private String str;}
获取配置文件中的属性值:
编写配置文件db.properties
jdbc.username=root
jdbc.password=123456
spring核心配置文件扫描配置文件
<context:property-placeholder location="db.properties"></context:property-placeholder>
注入配置文件中的属性值
@Value("${jdbc.username}")
private String username;@Value("${jabc.password}")
private String password;
注解实现IOC_@Configuration、@ComponentScan、@PropertySource
基于注解的IOC配置已经完成,但是依然离不开Spring的xml配置文件。接下来脱离bean.xml,使用纯注解实现IOC。纯注解实现IOC需要一个Java类代替xml文件。
在真实开发中,一般还是会保留xml配置文件,很多情况下使用配置文件更加方便。
@Configuration
作用:表示该类是一个配置类,作用是代替配置文件。
位置:类上方
@Configuration
public class SpringConfig{
}
@ComponentScan
作用:指定spring在初始化容器时扫描的包。
位置:配置类上方
@Configuration
@ComponentScan("com.spring")
public class SpringConfig{}
@PropertySource
作用:代替配置文件中的 < context:property-placeholder>扫描配置文件
位置:配置类上方
注意:配置文件位置前要加关键字 classpath
@Configuration
@PropertySource("classpath:db.properties")
public class JdbcConfig{@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;
}
测试时,构建Spring容器需要创建 AnnotationConfigApplicationContext对象
@Test
public void t4(){ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfig.class);StudentService studentService=ac.getBean(StudentService.class);System.out.println(studentService);}
注解实现IOC_@Bean
作用:将方法的返回值对象放入Spring容器中。
位置:配置类的方法上方。
属性:name:给bean对象设置id。
@Configuration
@ComponentScan("com.spring")
@PropertySource("classpath:db.properties")
public class SpringConfig{@Beanpublic StudentService getStudentService(){return new StudentService();}
}
如果想将第三方类的对象放入容器,可以使用@Bean
- @Bean修饰的方法如果有参数,Spring会根据参数类型从容器中查找可用对象
- 如果容器中有多个该类型的对象,可以在参数前加 @Qualifier指定对象的id。
@Configuration
@ComponentScan("com.spring")
@PropertySource("classpath:db.properties")
public class SpringConfig{@Beanpublic StudentService getStudentService(@Qualifier("StudentDaoImpl") StudentDao studentDao){System.out.println(studentDao);return new StudentService();}
}
注解实现IOC_@Import
作用:如果配置过多,会有多个配置类,该注解可以为主配置类导入其他配置类
位置:主配置类上方
//Service配置类
@Configuration
public class ServiceConfig{@Beanpublic StudentService getStudentService(@Qualifier("studentDaoImpl2") StudentDao studentDao){System.out.println(studentDao);return new StudentService();}
}//主配置类
@Configuration
@ComponentScan("com.spring")
@Import(JdbcConfig.class)
public class SpringConfig{
}
Spring整合MyBatis_创建项目
使用MyBatis时需要写大量创建 SqlSessionFactoryBuilder、SqlSessionFactory、 SqlSession等对象的代码,而Spring的作用是帮助创建和管理对象,所以可以使用Spring整合MyBatis,简化MyBatis开发。
创建maven项目,引入依赖。
<dependencies>
<!-- mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.5</version></dependency>
<!-- mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.27</version></dependency>
<!-- druid--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.16</version></dependency>
<!-- spring--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.11</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>6.0.11</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>6.0.11</version></dependency>
<!-- junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version><scope>test</scope></dependency>
<!-- Mybatis与Spring的整合包,该包可以让Spring创建Mybatis的对象--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>3.0.2</version></dependency></dependencies>
Spring整合MyBatis_编写配置文件
- 编写数据库配置文件db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///db1
jdbc.username=root
jdbc.password=1234
- 创建MyBatis配置文件SqlMapConfig.xml,数据源、扫描接口都交由Spring管理,不需要在MyBatis配置文件中设置。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration></configuration>
- 创建Spring配置文件applicationContext.xml
<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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd">
<!-- 包扫描--><context:component-scan base-package="com.summer"></context:component-scan>
<!-- 读取配置文件--><context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 创建druid数据源对象--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}"></property><property name="url" value="${jdbc.url}"></property><property name="username" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property></bean>
<!-- Spring创建封装过的SqlSessionFactory--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property></bean>
<!-- Spring创建封装过的SqlSession--><bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/></bean>
</beans>
Spring整合MyBatis_编写Java代码
准备数据库
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (`sid` int(11) NOT NULL,`name` varchar(20) NOT NULL,`age` int(11) NOT NULL,`sex` char(1) DEFAULT NULL,`classId` int(11) DEFAULT NULL,PRIMARY KEY (`sid`),KEY `fk_id` (`classId`),CONSTRAINT `fk_id` FOREIGN KEY (`classId`) REFERENCES `classes` (`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `student` VALUES ('1', '占星魔仙', '1000', '女', '2');
INSERT INTO `student` VALUES ('2', '魔仙女王', '10000', '女', '2');
INSERT INTO `student` VALUES ('3', '美琪', '12', '女', '1');
INSERT INTO `student` VALUES ('4', '美雪', '11', '女', '1');
INSERT INTO `student` VALUES ('5', '小灰灰', '6', '男', '3');
INSERT INTO `student` VALUES ('6', '喜羊羊', '6', '男', '3');
INSERT INTO `student` VALUES ('7', '熊大', '5', '男', '4');
INSERT INTO `student` VALUES ('8', '翠花', '5', '女', '4');
准备实体类
public class Student {private int sid;private String name;private int age;private char sex;private int classId;//省略构造方法/getter/setter/toString}
编写持久层接口
@Repository
public interface StudentDao {//查询所有学生@Select("select * from student")List<Student> findAll();
}
编写service类
@Service
public class StudentService {//sqlSession对象@Autowiredprivate SqlSessionTemplate sqlSession;//使用SqlSession获取代理对象public List<Student> findAllStudent(){StudentDao studentDao=sqlSession.getMapper(StudentDao.class);return studentDao.findAll();}
}
Spring整合MyBatis_单元测试
1.引入Junit和Spring整合依赖
<!-- spring整合测试模块--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>6.0.11</version></dependency>
2、编写测试类
//JUnit使用Spring方式运行代码,即自动创建Spring
@RunWith(SpringJUnit4ClassRunner.class)
//告知创建spring容器时读取哪个配置类或配置文件
//配置类写法:@ContextConfiguration(classes=配置类.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class StudentServiceTest {@Autowiredprivate StudentService studentService;@Testpublic void testFindAll(){List<Student> allStudent=studentService.findAllStudent();allStudent.forEach(System.out::println);}
}
使用SqlSessionTemplate创建代理对象还是需要注册接口或者映射文件的。
- 在MyBatis配置文件注册接口
<configuration><mappers><mapper class="com.summer.dao.StudentDao"></mapper></mappers></configuration>
- 创建sqlSessionFactory时指定MyBatis配置文件
<!-- 创建Spring封装过的SqlSessionFactoryBean--><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_自动创建代理对象
Spring提供了MapperScannerConfigurer对象,该对象可以自动扫描包创建代理对象,并将代理对象放入容器中,此时不需要使用SqlSession手动创建代理对象。
- 创建MapperScannerConfigurer对象
<!-- 该对象可以自动扫描持久层接口,并为接口创建代理对象--><bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置扫描的接口包--><property name="basePackage" value="com.summer.dao"></property></bean>
- Service类直接使用代理对象即可
@Service
public class StudentService {@Autowiredprivate StudentDao studentDao;public void addStudent(Student student){studentDao.add(student);}
}
- 测试
@Testpublic void testAdd(){Student student=new Student(10,"灰太狼",12,'男',1);studentService.addStudent(student);}
AOP_AOP简介
AOP的全称是Aspect Oriented Programming,即面向切面编程。是实现功能统一维护的一种技术,它将业务逻辑的各个部分进行隔离,使开发人员在编写业务逻辑时可以专心于核心业务,从而提高了开发效率。
- 作用:在不修改源码的基础上,对已有方法进行增强。
- 实现原理:动态代理技术。
- 优势:减少重复代码、提高开发效率、维护方便
- 应用场景:事务处理、日志管理、权限控制、异常处理等方面。
AOP_AOP相关术语
名称 | 说明 |
---|---|
Joinpoint(连接点) | 指能被拦截到的点,在Spring中只有方法能被拦截。 |
Pointcut(切点) | 被增强的方法。 |
Advice(通知) | 切点被拦截后执行的方法。 |
Aspect(切面) | 切点+通知称为切面 |
Target(目标) | 被代理的对象 |
Proxy(代理) | 代理对象 |
Weaving(织入) | 生成代理对象的过程 |
AOP_AOP入门
AspectJ是一个基于Java语言的AOP框架,在Spring框架中建议使用AspectJ实现AOP。
- 引入依赖
<!-- spring--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.11</version></dependency>
<!-- junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency>
<!-- AspectJ--><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.7</version></dependency>
<!-- spring整合测试模块--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>6.0.11</version></dependency>
- 编写连接点
@Repository
public class UserDao {public void add(){System.out.println("用户新增");}public void delete(){System.out.println("用户删除");}public void update(){System.out.println("用户修改");}
}
- 编写通知类
public class MyAspectJAdvice{//后置通知public void myAfterReturning(){System.out.println("打印日志....");}
}
- 配置切面
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 包扫描--><context:component-scan base-package="com.summer"></context:component-scan><bean id="myAspectJAdvice" class="com.summer.advice.MyAspectJAdvice"></bean>
<!-- 配置AOP--><aop:config>
<!-- 配置切面--><aop:aspect ref="myAspectJAdvice">
<!-- 配置切点--><aop:pointcut id="myPointcut" expression="execution(* com.summer.dao.UserDao.*(..))"/><!-- 配置后置通知--><aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut"/></aop:aspect></aop:config>
</beans>
</beans>
- 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations =
"classpath:applicationContext.xml")
public class UserDaoTest {@Autowiredprivate UserDao userDao;@Testpublic void testAdd(){userDao.add();}@Testpublic void testDelete(){userDao.delete();}@Testpublic void testUpdate(){userDao.update();}
}
AOP_通知类型
AOP有以下几种常用的通知类型:
通知类型 | 描述 |
---|---|
前置通知 | 在方法执行前添加功能 |
后置通知 | 在方法正常执行后添加功能 |
异常通知 | 在方法抛出异常后添加功能 |
最终通知 | 无论方法是否抛出异常,都会执行该通知 |
环绕通知 | 在方法执行前后添加功能 |
- 编写通知方法
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;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 e){System.out.println("异常通知...");System.err.println(e.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;}
}
- 配置切面
<bean id="myAspectJAdvice" class="com.summer.advice.MyAspectJAdvice"></bean>
<!-- 配置AOP--><aop:config>
<!-- 配置切面--><aop:aspect ref="myAspectJAdvice">
<!-- 配置切点--><aop:pointcut id="myPointcut" expression="execution(* com.summer.dao.UserDao.*(..))"/>
<!--前置通知--><aop:before method="myBefore" pointcut-ref="myPointcut"/>
<!-- 后置通知--><aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut"/>
<!-- 异常通知--><aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointcut" throwing="e"/>
<!-- 最终通知--><aop:after method="myAfter" pointcut-ref="myPointcut"></aop:after>
<!-- 环绕通知--><aop:around method="myAround" pointcut-ref="myPointcut"></aop:around></aop:aspect></aop:config>
</beans>
AOP_切点表达式
AspectJ需要使用切点表达式配置切点位置,写法如下:
标准写法:方法的访问修饰符 方法返回值 包名.类名.方法名(参数列表)
访问修饰符可以省略。
返回值使用 *代表任意类型。
包名使用 * 表示任意包,多级包结构要写多个 * ,使用*..
表示任意包结构
类名和方法名都可以用 * 实现通配。
参数列表
- 基本数据类型直接写类型
- 引用类型写包名.类名
- *表示匹配一个任意类型参数
..
表示匹配任意类型任意个数的参数- 全通配:
* *..*.*(..)
AOP_多切面配置
可以为切点配置多个通知,形成多切面,比如希望dao层的每个方法结束后都可以打印日志并发送邮件:
- 编写发送邮件的通知:
public class MyAspectJAdvice2 {//后置通知public void myAfterReturning(JoinPoint joinPoint){System.out.println("发送邮件");}
}
- 配置切面:
<bean id="myAspectJAdvice2" class="com.summer.advice.MyAspectJAdvice2"></bean><aop:aspect ref="myAspectJAdvice2"><aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut"></aop:after-returning></aop:aspect>
AOP_注解配置AOP
Spring可以使用注解代替配置文件配置切面:
- 在xml中开启AOP注解支持
<!--开启注解配置Aop--><aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- 在通知类上方加入注解 @Aspect
@Aspect
@Component
public class MyAspectJAdvice {
}
- 在通知方法上方加入注解
@Aspect
@Component
public class MyAspectJAdvice {//后置通知@AfterReturning("execution(* com.summer.advice.MyAspectJAdvice.*(..))")public void myAfterReturning(JoinPoint joinpoint){System.out.println("切点方法名:"+joinpoint.getSignature().getName());System.out.println("目标对象:"+joinpoint.getTarget());System.out.println("打印日志:"+joinpoint.getSignature().getName()+"方法被执行了!");}//前置通知@AfterReturning("execution(* com.summer.advice.MyAspectJAdvice.*(..))")public void myBefore(){System.out.println("前置通知....");}//异常通知@AfterThrowing(value = "execution(* com.summer.advice.MyAspectJAdvice.*(..))",throwing ="e")public void myAfterThrowing(Exception e){System.out.println("异常通知...");System.err.println(e.getMessage());}//最终通知@After("execution(* com.summer.advice.MyAspectJAdvice.*(..))")public void myAfter(){System.out.println("最终通知");}//环绕通知@Around("execution(* com.summer.advice.MyAspectJAdvice.*(..))")public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{System.out.println("环绕前");Object obj=proceedingJoinPoint.proceed();//执行方法System.out.println("环绕后");return obj;}
}
- 测试:
public class UserDaoTest {@Autowiredprivate UserDao userDao;@Testpublic void testAdd(){userDao.add();`在这里插入代码片`}
如何为一个类下的所有方法统一配置切点:
- 在通知类中添加方法配置切点
@Pointcut("execution(* com.summer.dao.UserDao.*(..))")
public void pointCut(){}
- 在通知方法上使用定义好的切点
@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.summer")
@EnableAspectJAutoProxypublic
class SpringConfig {
}
AOP_原生Spring实现AOP
除了AspectJ,Spring本身也是可以实现AOP的。Spring原生方式实现AOP时,只支持四种通知类型:
通知类型 | 实现接口 |
---|---|
前置通知 | MethodBeforeAdvice |
后置通知 | AfterReturningAdvice |
异常通知 | ThrowsAdvice |
环绕通知 | MethodInterceptor |
引入依赖
<dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>6.0.11</version></dependency>
编写通知类
public class SpringAopAdvice implements MethodBeforeAdvice,AfterReturningAdvice, ThrowsAdvice, MethodInterceptor {/*** 环绕通知* @param invocation 目标方法* @return* @throws Throwable*/@Overridepublic Object invoke(MethodInvocation invocation) throws Throwable {System.out.println("环绕前");Object procced=invocation.proceed();System.out.println("环绕后");return procced;}/*** 后置通知* @param returnValue 目标方法的返回值* @param method 目标方法* @param args 参数列表* @param target 目标对象* @throws Throwable*/@Overridepublic void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {System.out.println("后置通知");}/*** 前置通知* @param method 目标方法* @param args 目标方法的参数列表* @param target 目标对象* @throws Throwable*/@Overridepublic void before(Method method, Object[] args, Object target) throws Throwable {System.out.println("前置通知");}/*** 异常通知* @param e 异常对象*/public void afterThrowing(Exception e){System.out.println("发送异常");}}
编写配置类
<!-- 包扫描--><context:component-scan base-package="com.summer"></context:component-scan><!-- 通知对象--><bean id="springAopAdvice" class="com.summer.advice.SpringAopAdvice"></bean><!-- 配置代理对象--><bean id="userDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean"><!-- 配置目标对象--><property name="target" ref="userDao"></property><!-- 配置通知--><property name="interceptorNames"><list><value>springAopAdvice</value></list></property><!-- 代理对象的生成方式 true:使用CGLib false:使用原生JDK生成--><property name="proxyTargetClass" value="true"></property></bean>
编写测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserDaoTest4 {@Autowired@Qualifier("userDaoProxy")private UserDao userDao;@Testpublic void testAdd(){userDao.add();}
}
AOP_SchemaBased实现AOP
SchemaBased(基础模式)配置方式是指使用Spring原生方式定义通知,而使用AspectJ框架配置切面。
编写通知类
package com.summer.advice;import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;import java.lang.reflect.Method;public class SpringAop implements MethodBeforeAdvice, AfterReturningAdvice
, ThrowsAdvice, MethodInterceptor {@Overridepublic Object invoke(MethodInvocation invocation) throws Throwable {System.out.println("环绕前");Object proceed=invocation.proceed();System.out.println("环绕后");return proceed;}@Overridepublic void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {System.out.println("后置通知");}@Overridepublic void before(Method method, Object[] args, Object target) throws Throwable {System.out.println("前置通知");}
}
配置切面
<context:component-scan base-package="com.summer"></context:component-scan><!-- 定义一个名为sampleBean的Bean,类型为com.example.SampleClass -->
<bean id="SpringAop" class="com.summer.advice.SpringAop"></bean><aop:config><aop:pointcut id="myPointcut" expression="execution(* com.summer.dao.UserDao.*(..))"/><aop:advisor advice-ref="SpringAop" pointcut-ref="myPointcut"/></aop:config></beans>
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class UserDao5 {@Qualifier("userDao")@Autowiredprivate UserDao userDao1;@Testpublic void testAdd(){userDao1.add();}}
Spring事务_事务简介
事务:不可分割的原子操作。即一系列的操作要么同时成功,要么同时失败。
开发过程中,事务管理一般在service层,service层中可能会操作多次数据库,这些操作是不可分割的。否则当程序报错时,可能会造成数据异常。
如:张三给李四转账时,需要两次操作数据库:张三存款减少、李四存款增加。如果这两次数据库操作间出现异常,则会造成数据错误。
- 准备数据库
CREATE TABLE account(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(20) DEFAULT NULL,
balance DOUBLE DEFAULT 0.0
)
INSERT INTO account VALUES(1,'熊大',1000),(2,'熊二',1000);
- 创建maven项目,引入依赖
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.11</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>6.0.11</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>6.0.11</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>6.0.11</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.27</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.5</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.16</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>3.0.2</version></dependency>
- 创建配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"><!-- 包扫描--><context:component-scan base-package="com.summer"></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:///db1"></property><property name="username" value="root"></property><property name="password" value="1234"></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.summer.dao"></property></bean></beans>
- 编写Java代码
public class Account {private int id;private String username;private double balance;
//省略构造方法、getter()、setter()和toString()方法
}
- 测试转账
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class AccountServiceTest {@Autowiredprivate AccountService accountService;@Testpublic void testTransfer(){accountService.transfer(1,2,5000);}
}
此时没有事务管理,会造成张三的余额减少,而李四的余额并没有增加。所以事务处理位于业务层,即一个service方法是不能分割的。
Spring事务_Spring事务管理方案
在service层手动添加事务可以解决该问题:
@Service
public class AccountService {@Autowiredprivate SqlSessionTemplate sqlSession;@Autowiredprivate AccountDao accountDao;/*** 转账* @param id1 转出人id* @param id2 转入人id* @param price 金额*/public void transfer(int id1,int id2,double price){try {System.out.println(id1 + "的初始值:" + accountDao.fingById(id1).getBalance());System.out.println(id2 + "的初始值:" + accountDao.fingById(id2).getBalance());//转出人减少金额Account account = accountDao.fingById(id1);account.setBalance(account.getBalance() - price);accountDao.update(account);System.out.println(id1 + "的最终值:" + accountDao.fingById(id1).getBalance());int i = 1 / 0;//模拟程序出错//转入人增加余额Account account1 = accountDao.fingById(id2);account1.setBalance(account1.getBalance() + price);accountDao.update(account1);System.out.println(id2 + "的最终值:" + accountDao.fingById(id2).getBalance());sqlSession.commit();}catch (Exception e){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 进行事务管理。
- 引入依赖
<!-- 事务管理--><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>6.0.11</version></dependency>
<!-- AspectJ --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.7</version></dependency>
- 在配置文件中引入约束
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd
- 进行事务配置
<!-- 事物管理器--><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.summer.service.*.*(..))"/>
<!-- 配置通知--><aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor></aop:config>
Spring事务_事务控制的API
Spring进行事务控制的功能是由三个接口提供的,这三个接口是Spring实现的,在开发中我们很少使用到,只需要了解他们的作用即可:
PlatformTransactionManager接口
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:attributes></tx:advice>
tx:method 中的属性:
- name:指定配置的方法。 * 表示所有方法, find* 表示所有以find开头的方法。
- read-only:是否是只读事务,只读事务不存在数据的修改,数据库将会为只读事务提供一些优化手段,会对性能有一定提升,建议在查询中开启只读事务。
- timeout:指定超时时间,在限定的时间内不能完成所有操作就会抛异常。默认永不超时
- rollback-for:指定某个异常事务回滚,其他异常不回滚。默认所有异常回滚。
- no-rollback-for:指定某个异常不回滚,其他异常回滚。默认所有异常回滚。
- propagation:事务的传播行为
- isolation:事务的隔离级别
Spring事务_传播行为
事务传播行为是指多个含有事务的方法相互调用时,事务如何在这些方法间传播。
如果在service层的方法中调用了其他的service方法,假设每次执行service方法都要开启事务,此时就无法保证外层方法和内层方法处于同一个事务当中。
//method1的所有方法在同一个事物中
public void method1(){//此时会开启一个新事物,无法保证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支持使用注解配置声明式事务。用法如下:
- 注册事务注解驱动
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
- 在需要事务支持的方法或类上加@Transactional
@Service
//作用于类上时,该类的所有public方法将具有该类型的事物属性
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
public class AccountService {
// @Autowired
// private SqlSessionTemplate sqlSession;@Autowiredprivate AccountDao accountDao;/*** 转账* @param id1 转出人id* @param id2 转入人id* @param price 金额*///作用于方法上时,该方法都将具有该类型的食物属性@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)public void transfer(int id1,int id2,double price){System.out.println(id1 + "的初始值:" + accountDao.fingById(id1).getBalance());System.out.println(id2 + "的初始值:" + accountDao.fingById(id2).getBalance());//转出人减少金额Account account = accountDao.fingById(id1);account.setBalance(account.getBalance() - price);accountDao.update(account);System.out.println(id1 + "的最终值:" + accountDao.fingById(id1).getBalance());//转入人增加余额Account account1 = accountDao.fingById(id2);account1.setBalance(account1.getBalance() + price);accountDao.update(account1);System.out.println(id2 + "的最终值:" + accountDao.fingById(id2).getBalance());}
}
- 配置类代替xml中的注解事务支持:在配置类上方写
@EnableTranscationManagement
@Transactional
@ComponentScan("com.summer")
@EnableTransactionManagement
public class SpringConfig {@Beanpublic DataSource getDataSource(){DruidDataSource druidDataSource=new DruidDataSource();druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");druidDataSource.setUrl("jdbc:mysql:///spring");druidDataSource.setUsername("root");druidDataSource.setPassword("1234");return druidDataSource;}@Beanpublic SqlSessionFactoryBean getSqlSession(DataSource dataSource){SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource);return sqlSessionFactoryBean;}@Beanpublic MapperScannerConfigurer getMapperScanner(){MapperScannerConfigurer mapperScannerConfigurer=new MapperScannerConfigurer();mapperScannerConfigurer.setBasePackage("com.summer.dao");return mapperScannerConfigurer;}@Beanpublic DataSourceTransactionManager getTransactionManger(DataSource dataSource){DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();dataSourceTransactionManager.setDataSource(dataSource);return dataSourceTransactionManager;}
}
Spring Task_定时任务
定时任务即系统在特定时间执行一段代码,它的场景应用非常广泛:
- 购买游戏的月卡会员后,系统每天给会员发放游戏资源。
- 管理系统定时生成报表。
- 定时清理系统垃圾。
定时任务的实现主要有以下几种方式:
- Java自带的java.util.Timer类,这个类允许调度一个java.util.TimerTask任务。使用这种方式可以让程序按照某一个频度执行,但不能在指定时间运行。一般用的较少。
- Quartz。这是一个功能比较强大的的调度器,可以让程序在指定时间执行,也可以按照某一个频度执行,配置起来稍显复杂。
- Spring3.0以后自带Spring Task,可以将它看成一个轻量级的Quartz,使用起来比Quartz简单很多。
Spring Task_入门案例
- 创建Maven项目,引入Spring依赖
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.11</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.19</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>6.0.11</version></dependency>
- 编写定时要执行的方法
public class MySpringTask {public void printTime(){SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss");String now=simpleDateFormat.format(new Date());System.out.println(now);}
}
- 创建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"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"><context:component-scan base-package="com.fall"></context:component-scan><bean id="MySpringTask" class="com.fall.MySpringTask"></bean>
<!-- 配置执行定时任务--><task:scheduled-tasks><task:scheduled ref="MySpringTask" method="printTime" cron="* * * * * *"/></task:scheduled-tasks>
</beans>
- 编写测试类,读取Spring配置文件,开启定时任务
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) {new ClassPathXmlApplicationContext("applicationCOntext.xml");}
}
Spring Task_Cron表达式
Spring Task依靠Cron表达式配置定时规则。Cron表达式是一个字符串,分为6或7个域,每一个域代表一个含义,以空格隔开。有如下两种语法格式:
- Seconds Minutes Hours DayofMonth Month DayofWeek Year
- Seconds Minutes Hours DayofMonth Month DayofWeek
Seconds(秒):域中可出现
, - * /
四个字符,以及0-59的整数
*
:表示匹配该域的任意值,在Seconds域使用*
,表示每秒钟都会触发,
:表示列出枚举值。在Seconds域使用 5,20 ,表示在5秒和20秒各触发一次。-
:表示范围。在Seconds域使用 5-20 ,表示从5秒到20秒每秒触发一次
/
:表示起始时间开始触发,然后每隔固定时间触发一次。在Seconds域使用 5/20 , 表示5秒触发一次,25秒,45秒分别触发一次。
Minutes(分):域中可出现
, - * /
四个字符,以及0-59的整数
Hours(时):域中可出现
, - * /
四个字符,以及0-23的整数
DayofMonth(日期):域中可出现
, - * / ? L W C
八个字符,以及1-31的整数
- C :表示和当前日期相关联。在DayofMonth域使用 5C ,表示在5日后的那一天触发,且每月的那天都会触发。比如当前是10号,那么每月15号都会触发。
- L :表示最后,在DayofMonth域使用 L ,表示每个月的最后一天触发。
- W :表示工作日,在DayofMonth域用 15W ,表示最接近这个月第15天的工作日触发,如果15号是周六,则在14号即周五触发;如果15号是周日,则在16号即周一触发;如果15号是周二则在当天触发。
- 该用法只会在当前月计算,不会到下月触发。比如在DayofMonth域用 31W ,31号是周日,那么会在29号触发而不是下月1号。
- 在DayofMonth域用 LW ,表示这个月的最后一个工作日触发。
Month(月份):域中可出现
, - * /
四个字符,以及1-12的整数或JAN-DEC的单词缩写
DayofWeek(星期):可出现
, - * / ? L # C
八个字符,以及1-7的整数或SUN-SAT 单词缩写,1代表星期天,7代表星期六
- C :在DayofWeek域使用 2C ,表示在2天后的那一天触发,且每周的那天都会触发。比如当前是周一,那么每周三都会触发。
- L :在DayofWeek域使用 L ,表示在一周的最后一天即星期六触发。在DayofWeek域使用 5L ,表示在一个月的最后一个星期四触发。
#
:用来指定具体的周数, # 前面代表星期几, # 后面代表一个月的第几周,比如 5#3 表示一个月第三周的星期四。
? :在无法确定是具体哪一天时使用,用于DayofMonth和DayofWeek域。一般定义了其中一个域,另一个域是不确定的,比如每月20日触发,无法确定20日是星期几,写法如下:
0 0 0 20 *
? ;或者在每周一触发,此时无法确定该日期是几号,写法如下:0 0 0 ? * 2
Year(年份):域中可出现 , - * / 四个字符,以及1970~2099的整数。该域可以省略,表示每年都触发。
Spring Task_Cron实战案例
Spring Task_注解配置定时任务
可以使用注解的方式配置定时任务:
1.在Spring配置文件中开启注解任务,使注解生效:
<!-- 开启注解任务--><task:annotation-driven/>
- 在方法上方添加 @Scheduled ,指定该方法定时执行
//定时任务类
@Component
public class MySpringTask2 {
//打印时间@Scheduled(cron = "* * * * * *")public void printTime(){SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss");String now=simpleDateFormat.format(new Date());System.out.println(now+"定时任务2");}}
- 运行测试类
public class Test {public static void main(String[] args) {new AnnotationConfigApplicationContext(SpringConfig.class);}
}
- 在配置文件开启注解任务:在配置类上添加 @EnableScheduling 注解
@Configuration
@ComponentScan("com.fall")
@EnableScheduling
public class SpringConfig {
}
Spring Task_多线程任务
Spring Task定时器默认是单线程的,如果项目中使用多个定时器,使用一个线程会造成效率低下。代码如下:
//定时任务类
@Component
public class MySpringTask3 {//5秒才可以执行完任务1@Scheduled(cron = "* * * * * *")public void task1() throws InterruptedException{System.out.println(Thread.currentThread().getId()+"线程执行任务1");Thread.sleep(5000);}@Scheduled(cron = "* * * * * *")public void task2(){System.out.println(Thread.currentThread().getId()+"线程执行任务2");}
}
任务1较浪费时间,会阻塞任务2的运行。此时我们可以给Spring Task配置线程池。
@Configuration
@ComponentScan("com.fall")
@EnableScheduling
public class SpringConfig implements SchedulingConfigurer {@Overridepublic void configureTasks(ScheduledTaskRegistrar taskRegistrar) {//创建线程池taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));}
}
此时任务1不会阻塞任务2的运行。