Spring5学习
本学习笔记总结自【尚硅谷课程视频】php
1、Spring概念?
一、Spring框架概述
轻量级的开源的JavaEE框架。java
为简化企业级应用开发而生,解决企业应用开发的复杂性。使用Spring可使简单的JavaBean实现之前只有EJB才能实现的功能。mysql
Spring有两个核心部分:IOC和AOP。react
(1)IOC:控制反转,把建立对象过程交给Spring进行管理。
(2)AOP:面向切面,不修改源代码进行功能加强。ios
特色:c++
- 方便解耦,简化开发。IOC
- AOP编程支持。
- 方便程序的测试。
- 方便集成各类优秀框架。
- 方便进行事务操做。
- 下降Java EE API的使用难度。
- Java源码是经典学习范例。
二、入门案例
2.1 下载Spring
(1)使用Spring最新稳定版5.3.0
web
(2)下载地址spring
https://repo.spring.io/release/org/springframework/spring/sql
2.2 打开idea工具,建立普通Java工程
2.3 导入Spring5相关jar包
2.4 建立普通类,在这个类建立普通方法
public class User {
public void add(){
System.out.println("add...");
}
}
2.5 建立Spring配置文件,在配置文件配置建立的对象
(1)Spring配置文件使用xml格式。数据库
- 建立xml配置文件。
- 在配置文件中写上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">
<!-- 配置User类对象建立 -->
<bean id="user" class="com.spring5.User"></bean>
</beans>
2.6 进行测试代码编写
@Test
public void testAdd(){
//1.加载Spring配置文件
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
//2.获取配置建立的对象
User user = context.getBean("user", User.class);
System.out.println(user);
user.add();
}
2、IOC容器
一、IOC底层原理
1.1 什么是IOC?
(1)控制反转,把对象建立和对象之间的调用过程,交给Spring进行管理。
(2)使用IOC目的:为了耦合度下降。
(3)作入门案例就是IOC实现。
1.2 IOC底层原理
xml解析、工厂模式、反射。
1.3 画图讲解IOC底层原理
二、IOC接口(BeanFactory)
2.1 IOC思想基于IOC容器完成,IOC容器底层就是对象工厂
2.2 Spring提供IOC容器实现两种方式
(1)BeanFactory
IOC容器基本实现,是Spring内部的使用接口,不提供开发人员进行使用。
加载配置文件时候不会建立对象,在获取对象(使用)才去建立对象。
(2)ApplicationContext
BeanFactory接口的子接口,提供更强大的功能,通常由开发人员进行使用。
加载配置文件时候就会把在配置文件对象进行建立。
2.3 ApplicationContext接口有实现类
三、IOC操做Bean管理(基于xml)
3.1 什么是Bean管理
(1)Bean管理指的是两个操做。
(2)Spring建立对象。
(3)Spring注入属性。
3.2 Bean管理操做有两种方式
(1)基于XML配置文件方式实现。
(2)基于注解方式实现。
3.3 基于xml方式建立对象
<!-- 配置User类对象建立 -->
<bean id="user" class="com.spring5.User"></bean>
(1)在spring配置文件中,使用bean标签,标签里面添加对应属性,就能够实现对象建立。
(2)在bean标签有不少属性,介绍经常使用的属性。
- id属性:惟一标识。
- class属性:类全路径(包和类路径)。
(3)建立对象时候,默认也是执行无参数构造方法完成对象建立。
3.4 基于xml方式注入属性
(1)DI:依赖注入,就是注入属性。
(2)第一种注入方式:使用set方式进行注入。
- 建立类,定义属性和对应的set方法。
**
* 演示使用set方法进行注入属性
*/
public class Book {
//建立属性
private String bname;
private String bauthor;
//建立属性对应的set方法
public void setBname(String bname) {
this.bname = bname;
}
public void setBauthor(String bauthor) {
this.bauthor = bauthor;
}
}
- 在spring配置文件配置对象建立,配置属性注入。
<!-- set方法注入属性 -->
<bean id="book" class="com.spring5.Book">
<!-- 使用property完成属性注入
name:类里面属性名称
value:向属性注入的值。
-->
<property name="bname" value="易筋经"></property>
<property name="bauthor" value="达摩老祖"></property>
</bean>
(3)第二种注入方式:使用有参数构造进行注入。
- 建立类,定义属性,建立属性对应有参数构造方法。
/**
* 使用有参数构造注入
*/
public class Orders {
//属性
private String oname;
private String address;
//有参数构造
public Orders(String oname, String address) {
this.oname = oname;
this.address = address;
}
}
- 在spring配置文件中进行配置。
<!-- 有参数构造注入属性 -->
<bean id="orders" class="com.spring5.Orders">
<constructor-arg name="oname" value="电脑"></constructor-arg>
<constructor-arg name="address" value="China"></constructor-arg>
</bean>
(4)p名称空间注入(了解)。
- 使用p名称空间注入,能够简化基于xml配置方式。
第一步 添加p名称空间在配置文件中。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
第二步 进行属性注入,在bean标签里面进行操做
<!-- set方法注入属性 -->
<bean id="book" class="com.spring5.Book" p:bname="九阳神功" p:bauthor="无名氏">
</bean>
3.5 xml注入字符串,对象属性
(1)字面量。
- null值:
<!--null值-->
<property name="address">
<null/>
</property>
- 属性值包含特殊符号:
<!--属性值包含特殊符号
1 把<>进行转义
2 把带特殊符号内容写到CDATA
-->
<property name="address">
<value>
<![CDATA[<<南京>>]]>
</value>
</property>
(2)注入属性-外部bean
- 建立两个类service和dao类。
- 在service调用dao里面的方法。
- 在spring配置文件中进行配置。
public class UserService {
//建立UserDao类型属性,生成set方法
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void add(){
System.out.println("service add...");
userDao.update();
}
}
<!--1 service和dao对象建立-->
<bean id="userService" class="com.spring5.service.UserService">
<!--注入userDao对象
name属性值:类里面属性名称
ref属性:建立userDao对象bean标签id值
-->
<property name="userDao" ref="userDaoImpl"></property>
</bean>
<bean id="userDaoImpl" class="com.spring5.dao.UserDaoImpl"></bean>
(3)注入属性-内部bean
- 一对多关系:部门和员工。
一个部门有多个员工,一个员工属于一个部门。
部门是一,员工是多。
- 在实体类之间表示一对多关系。员工表示所属部门,使用对象类型属性进行表示。
//部门类
public class Dept {
private String dname;
public void setDname(String dname) {
this.dname = dname;
}
}
//员工类
public class Emp {
private String ename;
private String gender;
//员工属于某一个部门,使用对象形式表示
private Dept dept;
public void setEname(String ename) {
this.ename = ename;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setDept(Dept dept) {
this.dept = dept;
}
}
- 在spring配置文件中进行配置
<!--内部bean-->
<bean id="emp" class="com.spring5.bean.Emp">
<!--设置两个普通属性-->
<property name="ename" value="lucy"></property>
<property name="gender" value="女"></property>
<!--设置对象类型属性-->
<property name="dept">
<bean id="dept" class="com.spring5.bean.Dept">
<property name="dname" value="安保部"></property>
</bean>
</property>
</bean>
(4)注入属性-级联赋值
- 第一种写法
<!--级联赋值-->
<bean id="emp" class="com.spring5.bean.Emp">
<!--设置两个普通属性-->
<property name="ename" value="lucy"></property>
<property name="gender" value="女"></property>
<!--级联赋值-->
<property name="dept" ref="dept"></property>
</bean>
<bean id="dept" class="com.spring5.bean.Dept">
<property name="dname" value="财务部"></property>
</bean>
- 第二种写法
<!--级联赋值-->
<bean id="emp" class="com.spring5.bean.Emp">
<!--设置两个普通属性-->
<property name="ename" value="lucy"></property>
<property name="gender" value="女"></property>
<!--级联赋值-->
<property name="dept" ref="dept"></property>
<property name="dept.dname" value="技术部"></property>
</bean>
<bean id="dept" class="com.spring5.bean.Dept">
<property name="dname" value="财务部"></property>
</bean>
3.6 xml注入数组,List集合,Map集合属性
(1)注入数组类型属性。
(2)注入List集合类型属性。
(3)注入Map集合类型属性。
- 建立类,定义数组、list、map、set类型属性,生成对应set方法。
public class Stu {
//1 数组类型属性
private String[] courses;
//2 list集合类型属性
private List<String> list;
//3 map集合类型属性
private Map<String,String> maps;
//4 set集合类型属性
private Set<String> sets;
public void setCourses(String[] courses) {
this.courses = courses;
}
public void setList(List<String> list) {
this.list = list;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
public void setSets(Set<String> sets) {
this.sets = sets;
}
}
- 在spring配置文件进行配置。
<!--1 集合类型属性注入-->
<bean id="stu" class="com.spring5.collectiontype.Stu">
<!--数组类型属性注入-->
<property name="courses">
<array>
<value>java课程</value>
<value>数据库课程</value>
</array>
</property>
<!--list类型属性注入-->
<property name="list">
<list>
<value>张三</value>
<value>小三</value>
</list>
</property>
<!--map类型属性注入-->
<property name="maps">
<map>
<entry key="JAVA" value="java"></entry>
<entry key="PHP" value="php"></entry>
</map>
</property>
<!--set类型属性注入-->
<property name="sets">
<set>
<value>MySQL</value>
<value>Redis</value>
</set>
</property>
</bean>
(4)在集合里面设置对象类型值
<!--建立多个course对象-->
<bean id="course1" class="com.spring5.collectiontype.Course">
<property name="cname" value="Spring5框架"></property>
</bean>
<bean id="course2" class="com.spring5.collectiontype.Course">
<property name="cname" value="MyBatis框架"></property>
</bean>
<!--注入list集合类型,值是对象-->
<property name="courseList">
<list>
<ref bean="course1"></ref>
<ref bean="course2"></ref>
</list>
</property>
(5)把集合注入部分提取出来
- 在spring配置文件中引入名称空间util。
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/beans/spring-util.xsd">
</beans>
- 使用util标签完成list集合注入提取。
<!--1 提取list集合类型属性注入-->
<util:list id="bookList">
<value>易筋经</value>
<value>九阴真经</value>
<value>九阳神功</value>
</util:list>
<!--2 提取list集合类型属性注入使用-->
<bean id="book" class="com.spring5.collectiontype.Book">
<property name="list" ref="bookList"></property>
</bean>
3.7 FactoryBean
(1)Spring有两种类型bean,一种普通bean,另一种工厂bean(FactoryBean)。
(2)普通bean:在配置文件中定义bean类型就是返回类型。
(3)工厂bean:在配置文件中定义bean类型能够和返回类型不同。
- 第一步 建立类,让这个类做为工厂bean,实现接口FactoryBean。
- 第二部 实现接口里面的方法,在实现的方法中定义返回的bean类型。
public class MyBean implements FactoryBean<Course> {
//定义返回bean
@Override
public Course getObject() throws Exception {
Course course = new Course();
course.setCname("abc");
return course;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
//测试类
@Test
public void test3(){
ApplicationContext context =
new ClassPathXmlApplicationContext("bean3.xml");
Course course = context.getBean("myBean", Course.class);
System.out.println(course);
}
<!-- 配置文件 -->
<bean id="myBean" class="com.spring5.factorybean.MyBean">
</bean>
3.8 bean做用域
(1)在Spring里面,设置建立bean实例是单实例仍是多实例。
(2)在Spring里面,默认状况下,bean是单实例对象。
(3)如何设置单实例仍是多实例。
- 在spring配置文件bean标签里面有属性(scope)用于设置单实例仍是多实例。
- scope属性值:
第一个值 默认值,singleton,表示是单实例对象。
第二个值 prototype,表示是多实例对象。
- singleton和prototype区别
第一 singleton单实例,prototype多实例。
第二 设置scope值是singleton时候,加载spring配置文件时候就会建立单实例对象。设施scope值是prototype时候,不是在加载spring配置文件时候建立对象。在调用getBean方法时候建立多实例对象。
3.9 bean生命周期
(1)生命周期:
- 从对象建立到对象销毁的过程。
(2)bean生命周期:
- 经过构造器建立bean实例(无参数构造)。
- 为bean的属性设置值和对其余bean的引用(调用set方法)。
- 调用bean的初始化的方法(须要进行配置初始化的方法)。
- bean可使用了(对象获取到了)。
- 当容器关闭时候,调用bean的销毁的方法(须要进行配置销毁的方法)。
(3)演示bean生命周期:
public class Orders {
//无参数构造
public Orders(){
System.out.println("第一步 执行无参数构造建立bean实例");
}
private String oname;
public void setOname(String oname) {
this.oname = oname;
System.out.println("第二步 调用set方法设置属性值");
}
//建立执行的初始化的方法
public void initMethod(){
System.out.println("第三步 执行初始化的方法");
}
//建立执行的销毁的方法
public void destroyMethod(){
System.out.println("第五步 执行销毁的方法");
}
}
<!--配置文件-->
<bean id="orders" class="com.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
<property name="oname" value="手机"></property>
</bean>
//测试类
@Test
public void testBean3(){
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("bean4.xml");
Orders orders = context.getBean("orders", Orders.class);
System.out.println("第四步 获取建立bean实例对象");
System.out.println(orders);
//手动让bean实例销毁
context.close();
}
(4)bean的后置处理器(加上后),bean生命周期有七步。
- 经过构造器建立bean实例(无参数构造)。
- 为bean的属性设置值和对其余bean的引用(调用set方法)。
- 把bean实例传递bean后置处理器的方法。postProcessBeforeInitialization()。
- 调用bean的初始化的方法(须要进行配置初始化的方法)。
- 把bean实例传递bean后置处理器的方法。postProcessAfterInitialization()。
- bean可使用了(对象获取到了)。
- 当容器关闭时候,调用bean的销毁的方法(须要进行配置销毁的方法)。
(5)演示添加后置处理器效果。
- 建立类,实现接口BeanPostProcessor,建立后置处理器。
public class MyBeanPost implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化以前执行的方法");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化以后执行的方法");
return bean;
}
}
<!--配置后置处理器-->
<bean id="myBeanPost" class="com.spring5.bean.MyBeanPost"></bean>
3.10 xml自动装配
(1)什么是自动装配?
- 根据指定装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入。
(2)演示自动装配过程。
- 根据属性名称自动注入
<!--实现自动装配
bean标签属性autowire,配置自动装配
autowire属性经常使用两个值:
byName根据属性名称注入,注入值bean的id值和类属性名称同样
byType根据属性类型注入
-->
<bean id="emp" class="com.spring5.autowire.Emp" autowire="byName">
<!--<property name="dept" ref="dept"></property>-->
</bean>
<bean id="dept" class="com.spring5.autowire.Dept">
- 根据属性类型自动注入
<bean id="emp" class="com.spring5.autowire.Emp" autowire="byType">
<!--<property name="dept" ref="dept"></property>-->
</bean>
<bean id="dept" class="com.spring5.autowire.Dept">
</bean>
3.11 外部属性文件
(1)直接配置数据库信息。
- 配置德鲁伊链接池。
- 引入德鲁伊链接池依赖jar包
<!--直接配置链接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
(2)引入外部属性文件配置数据库链接池。
- 建立外部属性文件,properties格式文件,写数据库信息。
- 把外部properties属性文件引入到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" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
在spring配置文件使用标签引入外部属性文件。
<!--引入外部属性文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置链接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${prop.driverClass}"></property> <property name="url" value="${prop.url}"></property> <property name="username" value="${prop.userName}"></property> <property name="password" value="${prop.password}"></property> </bean>
四、IOC操做Bean管理(基于注解)
4.1 什么是注解?
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值…)。
(2)使用注解,注解做用在类上面,方法上面,属性上面。
(3)使用注解目的:简化xml配置。
4.2 Spring针对Bean管理中建立对象提供注解。
(1)@Componet
(2)@Service
(3)@Controller
(4)@Repository
上面四个注解功能是同样的,均可以用来建立bean实例。
4.3 基于注解方式实现对象建立
(1)第一步 引入依赖
(2)第二步 开启组件扫描
<!--开启组件扫描
1 若是扫描多个包,多个包使用逗号隔开
2 扫描包上层目录
-->
<context:component-scan base-package="com.spring5"></context:component-scan>
(3)第三步 建立类,在类上面添加建立对象注解。
//在注解里面value属性值能够省略不写,
//默认值是类名称,首字母小写
//UserService == userService
@Component(value = "userService") //<bean id="userService" class=".."/>等同
public class UserService {
public void add(){
System.out.println("service add...");
}
}
4.4 开启组件扫描细节配置
<!--示例1
use-default-filter="false" 表示如今不使用默认filter,本身配置filter。
context:include-filter,设置扫描哪些内容
-->
<context:component-scan base-package="com.spring5" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--示例2
下面配置扫描包全部内容
context:exclude-filter:设置哪些内容不进行扫描
-->
<context:component-scan base-package="com.spring5">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
4.5 基于注解方式实现属性注入
(1)@Autoired:根据属性类型进行自动装配
- 第一步 把service和dao对象建立,在service和dao类添加建立对象注解。
- 第二步 在service注入dao对象,在service类添加dao类型属性,在属性上面使用注解。
@Service
public class UserService {
//定义dao类型属性
//不须要添加set方法
//添加注入属性注解
@Autowired
private UserDao userDao;
public void add(){
System.out.println("service add...");
userDao.add();
}
}
(2)@Qualifier:根据属性名称进行注入
- 这个注解的使用,和上面@Autowired一块儿使用。
//定义dao类型属性
//不须要添加set方法
//添加注入属性注解
@Autowired //根据类型注入
@Qualifier(value = "userDaoImpl1")//根据名称进行注入
private UserDao userDao;
(3)@Resource:能够根据类型注入,能够根据名称注入。
//@Resource //根据类型进行注入
@Resource(name = "userDaoImpl1") //根据名称进行注入
private UserDao userDao;
(4)@Value:注入普通类型属性。
@Value(value = "abc")
private String name;
4.6 彻底注解开发
(1)建立配置类,替代xml配置文件。
@Configuration //做为配置类,替代xml配置文件
@ComponentScan(basePackages = {
"com.spring5"})
public class SpringConfig {
}
(2)编写测试类。
@Test
public void testService2(){
//加载配置类
ApplicationContext context
= new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
3、 AOP
一、概念
1.1 什么是AOP?
(1)面向切面编程(面向方面编程),利用AOP能够对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度下降,提升程序的可重用性,同时提升了开发的效率。
(2)通俗描述:不经过修改源代码方式,在主干功能里面添加新功能。
(3)使用登陆例子说明AOP。
二、底层原理
2.1 AOP底层使用动态代理
(1)有两种状况动态代理。
- 第一种 有接口状况,使用JDK动态代理
建立接口实现类代理对象,加强类的方法。
- 第二种 没有接口状况,使用CGLIB动态代理
建立子类的代理对象,加强类的方法。
2.2 JDK动态代理
(1)使用JDK动态代理,使用Proxy类里面的方法建立代理对象。
- 调用newProxyInstance方法
方法有三个参数:
第一个参数,类加载器。
第二个参数,加强方法所在的类,这个类实现的接口,支持多个接口。
第三个参数,实现这个接口InvocationHandler,建立代理对象,写加强的方法。
(2)编写JDK动态代理代码。
- 建立接口,定义方法。
public interface UserDao {
public int add(int a,int b);
public String update(String id);
}
- 建立接口实现类,实现方法。
public class UserDaoImpl implements UserDao{
@Override
public int add(int a, int b) {
return a+b;
}
@Override
public String update(String id) {
return id;
}
}
- 使用Proxy类建立接口代理对象。
public class JDKProxy {
public static void main(String[] args) {
//建立接口实现类代理对象
Class[] interfaces = {
UserDao.class};
// Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// return null;
// }
// });
UserDaoImpl userDao = new UserDaoImpl();
UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces,new UserDaoProxy(userDao));
int result = dao.add(1, 2);
System.out.println("result:" + result);
}
}
//建立代理对象代码
class UserDaoProxy implements InvocationHandler{
//1 把建立的是谁的代理对象,把谁传递过来
//有参数构造传递
private Object obj;
public UserDaoProxy(Object obj){
this.obj = obj;
}
//加强的逻辑
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法以前
System.out.println("方法以前执行..."+method.getName()+" :传递的参数..."+ Arrays.toString(args));
//被加强的方法执行
Object res = method.invoke(obj,args);
//方法以后
System.out.println("方法以后执行..."+obj);
return res;
}
}
三、术语
3.1 链接点
类里面哪些方法能够被加强,这些方法称为链接点。
3.2 切入点
实际被真正加强的方法,称为切入点。
3.3 通知(加强)
(1)实际加强的逻辑部分称为通知(加强)。
(2)通知有多种类型。
- 前置通知:方法以前执行。
- 后置通知:方法以后执行。
- 环绕通知:方法以前以后都执行。
- 异常通知:当方法出现异常时执行。
- 最终通知:相似于try catch中的finally。
3.4 切面
是动做。把通知应用到切入点过程。
四、准备
4.1 Spring框架通常都是基于AspectJ实现AOP操做
(1)什么是AspectJ?
- AspectJ不是Spring组成部分,独立AOP框架,通常把AspectJ和Spring框架一块儿使用,进行AOP操做。
4.2 基于AspectJ实现AOP操做
(1)基于xml配置文件实现。
(2)基于注解方式实现(使用)。
4.3 在项目工程里面引入AOP相关依赖
4.4 切入点表达式
(1)切入点表达式做用:知道对哪一个类里面的哪一个方法进行加强。
(2)语法结构:
execution([权限修饰符][返回类型][类全路径][方法名称]([参数列表]))
举例1:对com.spring5.dao.BookDao类里面的add进行加强。
execution(* com.spring5.dao.BookDao.add(..))
举例2:对com.spring5.dao.BookDao类里面的全部的方法进行加强。
execution(* com.spring5.dao.BookDao.*(..))
举例3:对com.spring5.dao包里面全部类,类里面全部方法进行加强。
execution(* com.spring5.dao.*.*(..))
五、AspectJ注解AOP操做
5.1 建立类,在类里面定义方法
public class User {
public void add(){
System.out.println("add...");
}
}
5.2 建立加强类(编写加强逻辑)
(1)在加强类里面,建立方法,让不一样方法表明不一样通知类型。
//加强的类
public class UserProxy {
//前置通知
public void before(){
System.out.println("before...");
}
}
5.3 进行通知的配置
(1)在spring配置文件中,开启注解扫描。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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.spring5.aopanno"></context:component-scan>
</beans>
(2)使用注解建立User和UserProxy对象。
(3)在加强类上面添加注解@Aspect。
(4)在spring配置文件中开启生成代理对象。
<!--开启AspectJ生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
5.4 配置不一样类型的通知
(1)在加强类的里面,在做为通知方法上面添加通知类型注解,使用切入点表达式配置。
//加强的类
@Component
@Aspect //生成代理对象
public class UserProxy {
//前置通知
//Before注解表示做为前置通知
@Before(value = "execution(* com.spring5.aopanno.User.add(..))")
public void before(){
System.out.println("before...");
}
//最终通知
@After(value = "execution(* com.spring5.aopanno.User.add(..))")
public void after(){
System.out.println("after...");
}
//后置通知(返回通知)
@AfterReturning(value = "execution(* com.spring5.aopanno.User.add(..))")
public void afterReturning(){
System.out.println("afterReturning...");
}
//异常通知
@AfterThrowing(value = "execution(* com.spring5.aopanno.User.add(..))")
public void afterThrowing(){
System.out.println("afterThrowing...");
}
//环绕通知
@Around(value = "execution(* com.spring5.aopanno.User.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("环绕以前...");
//被加强的方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕以后...");
}
}
5.5 相同的切入点抽取
//相同切入点抽取
@Pointcut(value = "execution(* com.spring5.aopanno.User.add(..))")
public void pointdemo(){
}
//前置通知
//Before注解表示做为前置通知
@Before(value = "pointdemo()")
public void before(){
System.out.println("before...");
}
5.6 有多个加强类对同一个方法进行加强,设置加强类的优先级
(1)在加强类上面添加注解@Order(数字类型值),数字类型值越小优先级越高。
@Component
@Aspect
@Order(1)
public class PersonProxy {
//前置通知
@Before(value = "execution(* com.spring5.aopanno.User.add(..))")
public void before(){
System.out.println("Person Before...");
}
}
5.7 彻底使用注解开发
(1)建立配置类,不须要建立xml配置文件。
@Configuration
//开启注解扫描
@ComponentScan(basePackages = {
"com.spring5"})
//开启AspectJ生成代理对象
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}
六、AspectJ配置文件AOP操做
6.1 建立两个类,加强类和被加强类,建立方法
//加强类
public class BookProxy {
public void before(){
System.out.println("before...");
}
}
//被加强类
public class Book {
public void buy(){
System.out.println("buy...");
}
}
6.2 在spring配置文件中建立两个类对象
<!--建立对象-->
<bean id="book" class="com.spring5.aopxml.Book"></bean>
<bean id="bookProxy" class="com.spring5.aopxml.BookProxy"></bean>
6.3 在spring配置文件中配置切入点
<!--配置aop加强-->
<aop:config>
<!--切入点-->
<aop:pointcut id="p" expression="execution(* com.spring5.aopxml.Book.buy(..))"/>
<!--配置切面-->
<aop:aspect ref="bookProxy">
<!--加强做用在具体的方法上-->
<aop:before method="before" pointcut-ref="p"/>
</aop:aspect>
</aop:config>
4、JDBCTemplate
一、概念和准备
1.1 什么是JdbcTemplate?
(1)Spring框架对JDBC进行封装,使用JdbcTemplate方便实现对数据库操做。
1.2 准备工做
(1)引入相关jar包。
(2)在spring配置文件配置数据库链接池。
<!--数据库链接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/user_db"></property>
<property name="username" value="root"></property>
<property name="password" value="admin"></property>
</bean>
(3)配置JdbcTemplate对象,注入DataSource。
<!--JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入DataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
(4)建立service类,建立dao类,在dao注入jdbcTemplate对象。
- 配置文件
<!--开启组件扫描-->
<context:component-scan base-package="com.spring5"></context:component-scan>
- Service
@Service
public class BookService {
//注入dao
@Autowired
private BookDao bookDao;
}
- Dao
@Repository
public class BookDaoImpl implements BookDao{
//注入JdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
}
二、操做数据库(添加)
2.1 对应数据库建立实体类
public class User {
private String userId;
private String username;
private String ustatus;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUstatus() {
return ustatus;
}
public void setUstatus(String ustatus) {
this.ustatus = ustatus;
}
}
2.2 编写service和dao
(1)在dao进行数据库添加操做。
(2)调用JdbcTemplate对象里面update方法实现添加操做。
有两个参数:
第一个参数:sql语句
第二个参数:可变参数,设置sql语句值。
//添加的方法
@Override
public void add(Book book) {
//1 建立sql语句
String sql = "insert into t_book value(?,?,?)";
//2 调用方法实现
Object[] args = {
book.getUserId(),book.getUsername(),book.getUstatus()};
int update = jdbcTemplate.update(sql,args);
System.out.println(update);
}
2.3 测试类
@Test
public void testJdbcTemplate(){
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book book = new Book();
book.setUserId("1");
book.setUsername("java");
book.setUstatus("a");
bookService.addBook(book);
}
三、操做数据库(修改和删除)
//一、修改
@Override
public void updateBook(Book book) {
String sql = "update t_book set username=?,ustatus=? where user_id=?";
Object[] args = {
book.getUsername(),book.getUstatus(),book.getUserId()};
int update = jdbcTemplate.update(sql, args);
System.out.println(update);
}
//二、删除
@Override
public void delete(String id) {
String sql = "delete from t_book where user_id=?";
int update = jdbcTemplate.update(sql, id);
System.out.println(update);
}
四、操做数据库(查询返回某个值)
4.1 查询表里面有多少条纪录,返回是某个值。
4.2 使用JdbcTemplate实现查询返回某个值代码。
有两个参数
第一个参数:sql语句。
第二个参数:返回类型Class。
//查询表记录数
@Override
public int selectCount() {
String sql = "select count(*) from t_book";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
五、操做数据库(查询返回对象)
5.1 场景:查询图书详情
5.2 JdbcTemplate实现查询返回对象
(1)有三个参数:
- 第一个参数:sql语句。
- 第二个参数:RowMapper,是接口,返回不一样类型数据,使用这个接口里面实现类完成数据封装。
- 第三个参数:sql语句值。
//查询返回对象
@Override
public Book findBookInfo(String id) {
String sql = "select * from t_book where user_id=?";
Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
return book;
}
六、操做数据库(查询返回集合)
6.1 场景:查询图书列表分页
6.2 调用JdbcTemplate方法实现实现查询返回集合
(1)有三个参数:
- 第一个参数:sql语句。
- 第二个参数:RowMapper是接口,针对返回不一样类型数据,使用这个接口里面实现类完成数据封装。
- 第三个参数:sql语句值。
//查询返回集合
@Override
public List<Book> findAllBook() {
String sql = "select * from t_book";
List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
return bookList;
}
七、操做数据库(批量操做)
7.1 批量操做:
操做表里面多条纪录。
7.2 JdbcTemplate实现批量添加操做
(1)有两个参数:
- 第一个参数:sql语句。
- 第二个参数:List集合,添加多条记录数据。
//批量添加
@Override
public void batchAddBook(List<Object[]> batchArgs) {
String sql = "insert into t_book values(?,?,?)";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
//测试
//批量添加
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {
"3","java","a"};
Object[] o2 = {
"4","c++","b"};
Object[] o3 = {
"5","MySQL","c"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用批量添加
bookService.batchAdd(batchArgs);
7.3 JdbcTemplate实现批量修改操做
//批量修改
@Override
public void batchUpdateBook(List<Object[]> batchArgs) {
String sql = "update t_book set username=?,ustatus=? where user_id=?";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
//测试
//批量修改
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {
"java0909","a3","3"};
Object[] o2 = {
"c++1010","b4","4"};
Object[] o3 = {
"MySQL1111","c5","5"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用方法实现批量修改
bookService.batchUpdate(batchArgs);
7.4 JdbcTemplate实现批量删除操做
//批量删除
@Override
public void batchDeleteBook(List<Object[]> batchArgs) {
String sql = "delete from t_book where user_id=?";
int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(ints));
}
//测试
//批量删除
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {
"3"};
Object[] o2 = {
"4"};
batchArgs.add(o1);
batchArgs.add(o2);
//调用方法实现批量删除
bookService.batchDelete(batchArgs);
5、事务管理
一、事务概念
1.1 什么是事务?
(1)事务是数据库操做最基本单元,逻辑上一组操做,要么都成功,若是有一个失败全部操做都失败。
(2)典型场景:银行转帐。
lucy转帐100元给mary
lucy少100,mary多100
1.2 事务四个特性(ACID)
(1)原子性:
(2)一致性:
(3)隔离性:
(4)持久性:
二、搭建事务操做环境
2.1 建立数据库表,添加记录。
2.2 建立service,搭建dao,完成对象建立和注入关系
(1)service注入dao,在dao注入JdbcTemplate,在JdbcTemplate注入DataSource。
@Service
public class UserService {
//注入dao
@Autowired
private UserDao userDao;
}
@Repository
public class UserDaoImpl implements UserDao {
//注入JdbcTemplate模板对象
@Autowired
private JdbcTemplate jdbcTemplate;
}
<!--开启组件扫描-->
<context:component-scan base-package="com.spring5"></context:component-scan>
<!--数据库链接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///user_db?characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="admin" />
</bean>
<!--JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入DataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
2.3 在dao建立两个方法:多钱和少钱的方法,在service建立方法(转帐的方法)。
//lucy转帐100给mary
//少钱
@Override
public void reduceMoney() {
String sql = "update t_account set money=money-? where username=?";
jdbcTemplate.update(sql,100, "lucy");
}
//多钱
@Override
public void addMoney() {
String sql = "update t_account set money=money+? where username=?";
jdbcTemplate.update(sql,100, "mary");
}
//转帐的方法
public void accountMoney(){
//lucy少100
userDao.reduceMoney();
//mary多100
userDao.addMoney();
}
2.4 上面代码,若是正常执行是没有问题的,可是若是代码执行过程当中出现异常,有问题。
(1)上面问题如何解决呢?
- 使用事务进行解决。
(2)事务操做过程。
三、Spring事务管理介绍
3.1 事务通常添加到JavaEE三层结构里面Service层(业务逻辑层)。
3.2 在Spring进行事务管理操做
(1)有两种方式:编程式事务管理和声明式事务管理(使用)
3.3 声明式事务管理
(1)基于注解方式
(2)基于xml配置文件方式
3.4 在Spring进行声明式事务管理,底层使用AOP原理
3.5 Spring事务管理API
(1)提供一个接口,表明事务管理器,这个借口针对不一样的框架提供不一样的实现类。
四、注解方式实现声明式事务管理
4.1 在spring配置文件配置事务管理器
<!--建立事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
4.2 在spring配置文件,开启事务注解
(1)在spring配置文件引入名称空间tx。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
(2)开启事务注解。
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
4.3 在service类上面(或者service类里面方法上面)添加事务注解
(1)@Transactional,这个注解添加到类上面,也能够添加到方法上面。
(2)若是把这个注解添加到类上面,这个类里面全部的方法都添加事务。
(3)若是把这个注解添加方法上面,为这个方法添加事务。
@Service
@Transactional
public class UserService {
}
五、声明式事务管理参数配置
5.1 在service类上面添加注解@Transactional,在这个注解里面能够配置事务相关参数
5.2 propagation:事务传播行为
(1)多事务方法之间进行调用,这个过程当中事务是如何进行管理的。
5.3 ioslation:事务隔离级别
(1)事务有特性称为隔离性,多事务操做之间不会产生影响。不考虑隔离性会产生不少问题。
(2)有三个读问题:脏读、不可重复读、虚(幻)读。
(3)脏读:一个未提交事务读取到另外一个未提交事务的数据。
(4)不可重复读:一个未提交事务读取到另外一提交事务修改数据。
(5)虚读:一个未提交事务读取到另外一提交事务添加数据。
(6)解决:经过设置事务隔离级别,解决读问题。
mysql默认使用REPEATABLE READ。
5.4 timeout:超时时间
(1)事务须要在必定时间内进行提交,若是不提交进行回滚。
(2)默认值是-1(不超时),设置时间以秒单位进行计算。
5.5 readOnly:是否只读
(1)读:查询操做,写:添加修改删除操做。
(2)readOnly默认值false,表示能够查询,能够添加修改删除操做。
(3)设置readOnly值是true,设置成true以后,只能查询。
5.6 rollbackFor:回滚
(1)设置出现哪些异常进行事务回滚。
5.7 noRollbackFor:不回滚
(1)设置出现哪些异常不进行事务回滚。
六、xml方式实现声明式事务管理
6.1 在spring配置文件中进行配置
(1)第一步 配置事务管理器。
<!--1 建立事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
(2)第二步 配置通知。
<!--2 配置通知-->
<tx:advice id="txadvice">
<!--配置事务参数-->
<tx:attributes>
<!--指定哪一种规则的方法上面添加事务-->
<tx:method name="accountMoney" propagation="REQUIRED"/>
<!--<tx:method name="account*"/>-->
</tx:attributes>
</tx:advice>
(3)第三步 配置切入点和切面。
<!--3 配置切入点和切面-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="pt" expression="execution(* com.spring5.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>
七、彻底注解声明式事务管理
7.1 建立配置类,使用配置类替代xml配置文件。
@Configuration //配置类
@ComponentScan(basePackages = "com.spring5") //组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
//建立数据库链接池
@Bean
public DruidDataSource getDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///user_db?characterEncoding=utf8");
dataSource.setUsername("root");
dataSource.setPassword("admin");
return dataSource;
}
//建立JdbcTemplate对象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
//到ioc容器中根据类型找到dataSource
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入dataSource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//建立事务管理器
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
6、Spring5新特性
一、整个Spring5框架的代码基于Java8,运行时兼容JDK9,许多不建议使用的类和方法在代码库中删除
二、Spring5框架自带了通用的日志封装
(1)Spring5已经移除Log4jConfigListener,官方建议使用Log4j2。
(2)Spring5框架整合Log4j2。
- 第一步 引入jar包。
- 第二步 建立Log4j2.xml配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status用于设置log4j2自身内部的信息输出,能够不设置,当设置成trace时,能够看到log4j2内部各类详细输出-->
<configuration status="INFO">
<!--先定义全部的appender-->
<appenders>
<!--输出日志信息到控制台-->
<console name="Console" target="SYSTEM_OUT">
<!--控制日志输出的格式-->
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</console>
</appenders>
<!--而后定义logger,只有定义了logger并引入的appender,appender才会生效-->
<!--root:用于指定项目的根日志,若是没有单独指定Logger,则会使用root做为默认的日志输出-->
<loggers>
<root level="info">
<appender-ref ref="Console"/>
</root>
</loggers>
</configuration>
三、Spring5框架核心容器支持@Nullable注解
(1)@Nullable注解可使用在方法上面,属性上面,参数上面,表示方法返回能够为空,属性值能够为空参数值能够为空。
(2)注解用在方法上面,方法返回值能够为空。
(3)注解使用在方法参数里面,方法返回值能够为空。
(4)注解使用在属性上。
四、Spring5核心容器支持函数式风格GeneriaApplicationContext
//函数式风格建立对象,交给spring进行管理
@Test
public void testGenericApplicationContext(){
//1 建立GeneriaApplicationContext对象
GenericApplicationContext context = new GenericApplicationContext();
//2 调用context的方法对象注册
context.refresh();
context.registerBean("user1",User.class,()->new User());
//3 获取在spring注册的对象
//User user = (User)context.getBean("com.spring5.test.User");
User user = (User)context.getBean("user1");
System.out.println(user);
}
五、Spring5支持整合JUnit5
5.1 整合JUnit4
(1)第一步 引入Spring相关针对测试依赖。
(2)第二步 建立测试类,使用注解方法完成。
@RunWith(SpringJUnit4ClassRunner.class) //单元测试框架
@ContextConfiguration("classpath:bean1.xml") //加载配置文件
public class JTest4 {
@Autowired
private UserService userService;
@Test
public void test1(){
userService.accountMoney();
}
}
5.2 Spring5整合JUnit5
(1)第一步 引入JUnit5的jar包。
(2)第二步 建立测试类,使用注解完成。
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean1.xml")
public class JTest5 {
@Autowired
private UserService userService;
@Test
public void test1(){
userService.accountMoney();
}
}
(3)使用一个复合注解替代上面两个注解完成整合
@SpringJUnitConfig(locations = "classpath:bean1.xml")
public class JTest5 {
@Autowired
private UserService userService;
@Test
public void test1(){
userService.accountMoney();
}
}
六、SpringWebflux
6.1 SpringWebflux介绍
(1)是Spring5添加新的模块,用于web开发的,功能与SpringMVC相似的,Webflux使用当前一种比较流行的响应式框架出现的框架。
(2)使用传统web框架,好比SpringMVC,这些基于Servlet容器,Webflux是一种异步非阻塞的框架,异步非阻塞的框架在Servlet3.1之后才支持,核心是基于Reactor(响应式编程)的相关API实现的。
(3)解释什么是异步非阻塞。
异步同步
非阻塞和阻塞
**上面都是针对对象不同
- 异步和同步针对调用者,调用者发送请求,若是等着对方回应以后才去作其余事情就是同步,若是发送请求以后不等着对方回应就去作其余事情就是异步。
- 阻塞和非阻塞针对被调用者,被调用者收到请求以后,作完请求任务以后才给出反馈就是阻塞,受到请求以后立刻给出反馈而后再去作事情就是非阻塞。
(4)Webflux特色:
- 第一 非阻塞式:在有限的资源下,提升系统吞吐量和伸缩性,以Reactor为基础实现响应式编程。
- 第二 函数式编程:Spring5框架基于java8,Webflux使用Java8函数式编程方法实现路由请求。
(5)比较SpringMVC。
- 第一 两个框架均可以使用注解方式,都运行在Tomcat等容器中。
- 第二 SpringMVC采用命令式编程,Webflux采用异步响应式编程。
6.2 响应式编程
(1)什么是响应式编程?
响应式编程是一种面向数据流和变化传播的编程范式,这意味着能够在编程语言中很方便地表达静态或动态的数据流,而相关的计算模型会自动将变化的值经过数据流进行传播。
电子表格程序就是响应式编程的一个例子,单元格能够包含字面值或相似“=B1+C1”的公式,而包含公式的单元格的值会依据其余单元格的值的变化而变化。
(2)Java8及其以前版本。
- 提供了观察者模式两个类Observer和Observable
public class ObserverDemo extends Observable {
public static void main(String[] args) {
ObserverDemo observer = new ObserverDemo();
//添加观察者
observer.addObserver((o,arg)->{
System.out.println("发生变化");
});
observer.addObserver((o,arg)->{
System.out.println("手动被观察者通知,准备改变");
});
observer.setChanged(); //数据变化
observer.notifyObservers(); //通知
}
}
(3)Reactor实现。
- 响应式编程操做中,Reactor是知足Reactive规范框架。
- Reactor有两个核心类,Mono和Flux,这两个类实现接口Publisher。Flux对象实现发布者,返回N个元素;Mono实现发布者,返回0或者1个元素。
- Flux和Mono都是数据流的发布者,使用Flux和Mono均可以发出三种数据信号:元素值,错误信号,完成信号。错误信号和完成信号都表明终止信号,终止信号用于告诉订阅者数据流结束了。错误信号终止数据流同时把错误信息传递给订阅者。
- 代码演示Flux和Mono
第一步 引入依赖
<dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-core</artifactId> <version>3.1.5.RELEASE</version> </dependency>
第二步 编写代码
public static void main(String[] args) { //just方法直接声明 Flux.just(1,2,3,4); Mono.just(1); //其余的方法 Integer[] array = { 1,2,3,4}; Flux.fromArray(array); List<Integer> list = Arrays.asList(array); Flux.fromIterable(list); Stream<Integer> stream = list.stream(); Flux.fromStream(stream); }
- 三种信号特色:
错误信号和完成信号都是终止信号,不能共存的。
若是没有发送任何元素值,而是直接发送错误或者完成信号,表示是空数据流。
若是没有错误信号,没有完成信号,表示是无限数据流。
- 调用just或者其余方法只是声明数据流,数据流并无发出,只有进行订阅以后才会触发数据流,不订阅什么都不会发生的。
//just方法直接声明
Flux.just(1,2,3,4).subscribe(System.out::print);
Mono.just(1).subscribe(System.out::print);
- 操做符。
对数据流进行一道道操做,称为操做符,好比工厂流水线。
第一 map 元素映射为新元素
第二 flatmap 元素映射为流
把每一个元素转换流,把转换以后多个流合并成大的流。
6.3 Webflux执行流程和核心API
SpringWebflux基于Reactor,默认容器是Netty,Netty是高性能,NIO框架,异步非阻塞的框架。
(1)Netty。
- BIO:
- NIO:
(2)SpringWebflux执行过程和SpringMVC类似。
- SpringWebflux核心控制器DispatchHandler,实现接口WebHandler。
- 接口WebHandler有一个方法。
- SpringWebflux里面DispatchHandler,负责请求的处理。
HandlerMapping:请求查询处处理的方法。
HandlerAdapter:真正负责请求处理。
HandlerResultHandler:响应结果处理。
- SpringWebflux实现函数式编程,两个接口:RouterFunction(路由处理)和HandlerFunction(处理函数)
6.4 SpringWebflux(基于注解编程模型)
SpringWebflux实现方式有两种:注解编程模型和函数式编程模型。
使用注解编程模型方式,和以前SpringMVC使用类似,只须要把相关依赖配置到项目中,SpringBoot自动配置相关运行容器,默认状况下使用Netty服务器。
第一步 建立SpringBoot工程,引入WebFlux依赖。
第二步 配置启动端口号。
第三步 建立包和相关类。
实体类:
建立接口定义操做方法:
接口实现类:
建立Controller:
说明:
SpringMVC方式实现,同步阻塞的方式,基于SpringMVC+Servlet+Tomcat。
SpringWebflux方式实现,异步非阻塞方式,基于SpringWebflux+Reactor+Netty。
6.5 SpringWebflux(基于函数式编程模型)
(1)在使用函数式编程模型操做时候,须要本身初始化服务器。
(2)基于函数式编程模型时候,有两个核心接口:RouterFunction(实现路由功能,请求转发给对应的handler)和HandlerFunction(处理请求生成响应的函数)。核心任务定义两个函数式接口的实现而且启动须要的服务器。
(3)SpringWebflux请求和响应再也不是ServletRequest和ServletResponse,而是ServerRequest和ServerResponse。
(4)编程实现。
- 第一步 把注解编程模型工程复制一份。
- 第二步 建立Handler(具体实现方法)。
public class UserHandler{
private final UserService userService;
public UserHandler(UserService userService){
this.userService = userService;
}
//根据id查询
public Mono<ServerResponse> getUserById(ServerRequest request){
//获取id值
int userId = Integer.valueOf(request.pathVariable("id"));
//空值处理
Mono<ServerResponse> notFound = ServerResponse.notFound().build();
//调用service方法获得数据
Mono<User> userMono = this.userService.getUserById(userId);
//把userMono进行转换返回
//使用Reactor操做符flatMap
return
userMono
.flatMap(person->ServerResponse.ok().contentType(MediaType.APPLICATION_JSON
.body(fromObject(person))))
.switchIfEmpty(notFound);
}
//查询全部
public Mono<ServerResponse> getAllUsers(){
//调用service获得结果
Flux<User> users = this.userService.getAllUser();
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(users,User.class);
}
//添加
public Mono<ServerResponse> saveUser(ServerRequest request){
//获得user对象
Mono<User> userMono = request.bodyToMono(User.class);
return ServerResponse.ok().build(this.userService.saveUserInfo(userMono));
}
}
- 第三步 初始化服务器,编写Router。
建立路由的方法。
public class Server{ //1 建立router路由 public RouterFunction<ServerResponse> routingFunction(){ //建立handler对象 UserService userServie = new UserServiceImpl(); UserHandler handler = new UserHandler(userServie); //设置路由 RouterFunction.route( GET("/users/{id}").and(accept(APPLICAION_JSON),handler::getUserById).andRoute(GET("/users").and(accept(APPLICAION_JSON)),handler::getAllUsers); ); } }
建立服务器,完成适配。
//2 建立服务器完成适配 public void createReactorServer(){ //路由和handler适配 RouterFunction<ServerResponse> route = routingFunction(); HttpHandler httpHandler = toHttpHandler(route); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); //建立服务器 HttpServer httpServer = HttpServer.create(); httpServer.handle(adapter).bindNow(); }
最终调用
public static void main(String[] args) throws Exception{ Server server = new Server(); server.createReactorServer(); System.out.println("enter to exit"); System.in.read(); }
- 使用WebClient调用
public class Client{
public static void main(String[] args){
//调用服务器地址
WebClient webClient = WebClient.create("http://127.0.0.1:5794");
//根据id查询
String id = "1";
User userresult = webClient.get().uri("/users/{id}",id)
.accept(MediaType.APPLICATION_JSON).retrieve().bodyToMono(User.class)
.block();
System.out.println(userresult.getName());
//查询全部
Flux<User> results = webClient.get().uri("/users")
..accept(MediaType.APPLICATION_JSON).retrieve().bodyToFlux(User.class);
results.map(stu -> stu.getName())
.buffer().doOnNext(System.out::println).blockFirst();
}
7、总结
一、Spring框架概述
(1)轻量级开源JavaEE框架,为了解决企业复杂性,两个核心组成:IOC和AOP。
(2)Spring5版本。
二、IOC容器
(1)IOC底层原理(工厂、反射等)。
(2)IOC接口(BeanFactory)。
(3)IOC操做Bean管理(基于xml)。
(4)IOC操做Bean管理(基于注解)。
三、AOP
(1)AOP底层原理:动态代理,有接口(JDK动态代理),没有接口(CGLIB动态代理)。
(2)术语:切入点、加强(通知)、切面。
(3)基于AspectJ实现AOP操做。
四、JdbcTemplate
(1)使用JdbcTemplate实现数据库curd操做。
(2)使用JdbcTemplate实现数据库批量操做。
五、事务管理
(1)事务概念。
(2)重要概念(传播行为和隔离级别)。
(3)基于注解实现声明式事务管理。
(4)彻底注解方式实现声明式事务管理。
六、Spring5新功能
(1)整合日志框架。
(2)@Nullable注释。
(3)函数式注册对象。
(4)整合JUnit5单元测试框架。
(5)SpringWebflux使用。