Spring基础知识整理

Spring

Spring是什么?

Spring是分层的JavaSE/EE应用 full-stack(一站式)轻量级开源框架.

IoC(控制反转)

⚫ 耦合(Coupling):代码书写过程中所使用技术的结合紧密度,用于衡量软件中各个模块之间的互联程度

⚫ 内聚(Cohesion):代码书写过程中单个模块内部各组成部分间的联系,用于衡量软件中各个功能模块内部的功能联系

⚫ 程序书写的目标:高内聚,低耦合

​ ◆ 就是同一个模块内的各个元素之间要高度紧密,但是各个模块之间的相互依存度却不要那么紧密

在这里插入图片描述

IoC

⚫ IoC(Inversion Of Control)控制反转,Spring反向控制应用程序所需要使用的外部资源

⚫ Spring控制的资源全部放置在Spring容器中,该容器称为IoC容器

⚫ 传统模式:主控权在类手中;IoC模式主动变被动;IoC容器主控权在spring中

⚫ 控制反转的意思就是:主动变被动

IoC入门案例

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> 				<version>5.1.9.RELEASE</version>
</dependency>
public interface UserService {
//业务方法
void save();
}
public class UserServiceImpl implements UserService{
//业务方法实现
	public void save(){
		System.out.println("user service running...");
	}
}
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- 1.创建spring控制的资源--> 
    <bean id="userService" class="com.itheima.service.impl.UserServiceImpl"/>
</beans>
public static void main(String[] args) {
	//2.加载配置文件
	ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
	//3.获取资源
	UserService userService = (UserService) ctx.getBean("userService");
	userService.save();
}

⚫ 入门案例步骤

  1. 加载spring

  2. 创建资源

  3. 配置资源

  4. 使用资源

bean

⚫ 名称:bean

⚫ 类型:标签

⚫ 归属:beans标签

⚫ 作用:定义spring中的资源,受此标签定义的资源将受到spring控制

⚫ 格式:

<beans> 
	<bean />
</beans>

⚫ 基本属性:

<bean id="beanId" name="beanName1,beanName2" class="ClassName"></bean>

​ ◆ id:bean的名称,通过id值获取bean

​ ◆ class:bean的类型

​ ◆ name:bean的名称,可以通过name值获取bean,用于多人配合时给bean起别名

不写默认是单例,使用场景,当方法中存在个性化时

单例对象在加载spring配置文件是创建

非单例对象是在获取对象时创建

他们的创建时机不同

bean属性scope

⚫ 名称:scope

⚫ 类型:属性

⚫ 归属:bean标签

⚫ 作用:定义bean的作用范围

⚫ 格式:

<bean scope="singleton"></bean>

⚫ 取值:

​ ◆ singleton:设定创建出的对象保存在spring容器中,是一个单例的对象

​ ◆ prototype:设定创建出的对象保存在spring容器中,是一个非单例的对象

​ ◆ request、session、application、 websocket :设定创建出的对象放置在web容器对应的位置

⚫ 注意事项:

​ ◆ 不写scope属性默认是单例

​ ◆ 使用场景,当方法中存在个性化时,需要去指定prototype

​ ◆ 单例对象在加载spring配置文件是创建

​ ◆ 非单例对象是在获取对象时创建

bean生命周期

⚫ 名称:init-method,destroy-method

⚫ 类型:属性

⚫ 归属:bean标签

⚫ 作用:定义bean对象在初始化或销毁时完成的工作

⚫ 格式:

<bean init-method="init" destroy-method="destroy></bean>

⚫ 取值:bean对应的类中对应的具体方法名

⚫ 注意事项:

​ ◆ 当scope=“singleton”时,spring容器中有且仅有一个对象,init方法在创建容器时仅执行一次

​ ◆ 当scope=“prototype”时,spring容器要创建同一类型的多个对象,init方法在每个对象创建时均执行一次

​ ◆ 当scope=“singleton”时,关闭容器会导致bean实例的销毁,调用destroy方法一次

​ ◆ 当scope=“prototype”时,对象的销毁由垃圾回收机制gc()控制,destroy方法将不会被执行

bean对象的创建方式(静态工厂)

⚫ 名称:factory-bean

⚫ 类型:属性

⚫ 归属:bean标签

⚫ 作用:定义bean对象创建方式,使用静态工厂的形式创建bean,兼容早期遗留系统的升级工作

⚫ 格式:

<bean class="FactoryClassName" factory-method="factoryMethodName"></bean>

⚫ 取值:工厂bean中用于获取对象的静态方法名

⚫ 注意事项:

​ ◆ class属性必须配置成静态工厂的类名

bean对象的创建方式(实例工厂)

⚫ 名称:factory-bean,factory-method

⚫ 类型:属性

⚫ 归属:bean标签

⚫ 作用:定义bean对象创建方式,使用实例工厂的形式创建bean,兼容早期遗留系统的升级工作

⚫ 格式:

<bean factory-bean="factoryBeanId" factory-method="factoryMethodName"></bean>

⚫ 取值:工厂bean中用于获取对象的实例方法名

⚫ 注意事项:

​ ◆ 使用实例工厂创建bean首先需要将实例工厂配置bean,交由spring进行管理

​ ◆ factory-bean是实例工厂的beanId

DI

⚫ IoC(Inversion Of Control)控制翻转,Spring反向控制应用程序所需要使用的外部资源

⚫ DI(Dependency Injection)依赖注入,应用程序运行依赖的资源由Spring为其提供,资源进入应用程序的方式称为注入

在这里插入图片描述

⚫ IoC与DI是同一件事站在不同角度看待问题

依赖注入的两种方式

⚫ set注入

⚫ 构造器注入

set注入(主流)

⚫ 名称:property

⚫ 类型:标签

⚫ 归属:bean标签

⚫ 作用:使用set方法的形式为bean提供资源

⚫ 格式:

<bean>
	<property />
</bean>

⚫ 基本属性:

<property name="propertyName" value="propertyValue" ref="beanId"/>

​ ◆ name:对应bean中的属性名,要求该属性必须提供可访问的set方法(严格规范为此名称是set方法对应名称)

​ ◆ value:设定非引用类型属性对应的值,不能与ref同时使用

​ ◆ ref:设定引用类型属性对应bean的id ,不能与value同时使用

⚫ 注意:一个bean可以有多个property标签

⚫ set注入

​ ◆ 使用封装中的set方法

​ ◆ bean中使用property标签注入属性

​ ◆ name表示注入的属性名

​ ◆ 对象:使用ref进行注入

​ ◆ 其他:使用value进行注入

构造器注入(了解)

⚫ 名称:constructor-arg

⚫ 类型:标签

⚫ 归属:bean标签

⚫ 作用:使用构造方法的形式为bean提供资源,兼容早期遗留系统的升级工作

⚫ 格式:

<bean>
	<constructor-arg />
</bean>

⚫ 基本属性:

<constructor-arg name="argsName" value="argsValue />

​ ◆ name:对应bean中的构造方法所携带的参数名

​ ◆ value:设定非引用类型构造方法参数对应的值,不能与ref同时使用

⚫ 注意:一个bean可以有多个constructor-arg标签

⚫ 其他属性:

<constructor-arg index="arg-index" type="arg-type" ref="beanId"/>

​ ◆ ref:设定引用类型构造方法参数对应bean的id ,不能与value同时使用

​ ◆ type :设定构造方法参数的类型,用于按类型匹配参数或进行类型校验

​ ◆ index :设定构造方法参数的位置,用于按位置匹配参数,参数index值从0开始计数

⚫ 构造器注入

​ ◆ 带参构造方法

​ ◆ bean中使用constructor-arg标签注入属性

​ ◆ name表示注入的属性名

​ ◆ 对象:使用ref进行注入

​ ◆ 其他:使用value进行注入

​ ◆ 支持按类型注入

​ ◆ 支持按顺序注入

集合类型数据注入

⚫ 名称:array,list,set,map,props

⚫ 类型:标签

⚫ 归属:property标签 或 constructor-arg标签

⚫ 作用:注入集合数据类型属性

⚫ 格式:

<property> 
	<list></list>
</property>
集合类型数据注入——list
<!--List集合类型注入数据-->
<property name="myList"> 
	<list>
		<value>itheima</value>
        <value>666</value> 
        <ref bean="userService"/>
		<bean class="com.itheima.service.ApplyService"/>
	</list>
</property>
集合类型数据注入——props
<!--Properties类型注入数据--> 
<property name="myProps"> 
	<props> 
		<prop key="username">root</prop>
		<prop key="password">root</prop>
	</props>
</property>
集合类型数据注入——array (了解)
<!--数组类型注入数据--> 
<property name="myArray"> 
	<array> 
		<value>itheima</value> 
		<value>666</value>
		<ref bean="userService"/>
		<bean class="com.itheima.service.ApplyService"/>
	</array>
</property>
集合类型数据注入——set(了解)
<!--Set集合类型注入数据-->
<property name="mySet"> 
	<set>
		<value>itheima</value> 
		<value>666</value>
		<ref bean="userService"/>
		<bean class="com.itheima.service.ApplyService"/>
	</set>
</property
集合类型数据注入——map(了解)
<!--Map集合类型注入数据-->
<property name="myMap">
	<map>
		<entry key="name" value-ref="itheima"/>
		<entry key="fame" value-ref="666"/>
		<entry key="userService"> 
			<ref bean="userService"></ref>
		</entry> <entry key="applyService">
        	<bean class="applyService"/>
		</entry>
	</map>
</property

properties文件

⚫ Spring提供了读取外部properties文件的机制,使用读取到的数据为bean的属性赋值

⚫ 操作步骤

  1. 准备外部properties文件

  2. 开启context命名空间支持

xmlns:context="http://www.springframework.org/schema/context" 
  1. 加载指定的properties文件
<context:property-placeholder location="classpath:filename.properties"> 
  1. 使用加载的数据
<property name="propertyName" value="${propertiesName}"/> 

⚫ 注意:如果需要加载所有的properties文件,可以使用*.properties表示加载所有的properties文件

⚫ 注意:读取数据使用${propertiesName}格式进行,其中propertiesName指properties文件中的属性名

BeanFactory和ApplicationContext的区别

  • 通过类视图我们可以看出,BeanFactory是Spring中IoC容器的顶层接口,而ApplicationContext是它的一个子接口,所以ApplicationContext具备BeanFactory提供的全部功能。

    通常情况下,我们称BeanFactory是Spring的IoC基础容器。而ApplicationContext是容器的高级接口,它比BeanFactory多了很多重要的功能。例如,父子容器的概念(在SpringMVC课程中讲解),AOP的支持,消息发布机制,事件处理机制,国际化和资源访问等等。

  • BeanFactory 和 ApplicationContext 的区别:

    • 创建对象的时间点不一样。
      • ApplicationContext:只要一读取配置文件, 默认情况下就会创建对象。
      • BeanFactory:什么使用什么时候创建对象

spring整合

  • 整合 : 就是把相应技术的关键类对象存放到spring容器中

spring注解开发

bean标签和注解的对应

  • bean标签对应注解@Component

    • 注解属性value:bean标签的id属性
    • 不指定value属性,默认就是类名,首字母小写
    • 该注解衍生出了三个注解,@Controller,@Service,@Repository,用法和@Componet一致,为了更加清晰的提现层的概念。
  • bean标签属性scope对应注解@Scope

    • 注解属性value:singleton,prototype
  • bean标签属性init-method对应注解@PostConstruct

  • bean标签属性destroy-method对应注解@PreDestroy

  • 启动注解扫描,加载类中配置的注解项

    <context:component-scan base-package="packageName"/>
    

AOP

AOP概念

⚫ AOP(Aspect Oriented Programing)面向切面编程,一种编程范式,隶属于软工范畴,指导开发者如

何组织程序结构

⚫ AOP弥补了OOP的不足,基于OOP基础之上进行横向开发

​ ◆ OOP规定程序开发以类为主体模型,一切围绕对象进行,完成某个任务先构建模型

​ ◆ AOP程序开发主要关注基于OOP开发中的共性功能,一切围绕共性功能进行,完成某个任务先构建可能遇到的所有共性功能(当所有功能都开发出来也就没有共性与非共性之分)

⚫ “AOP联盟”

AOP作用

⚫ 伴随着AOP时代的降临,可以从各个行业的标准化、规范化开始入手,一步一步将所有共性功能逐一开发完毕,最终以功能组合来完成个别业务模块乃至整体业务系统的开发

⚫ 目标:将软件开发由手工制作走向半自动化/全自动化阶段,实现“插拔式组件体系结构”搭建

AOP优势

⚫ 提高代码的可重用性

⚫ 业务代码编码更简洁

⚫ 业务代码维护更高效

⚫ 业务功能扩展更便捷

AOP术语

名词解释
Joinpoint(连接点)它指的是那些可以用于把增强代码加入到业务主线中的点,那么由上图中我们可以看出,这些点指的就是方法。在方法执行的前后通过动态代理技术加入增强的代码。在Spring框架AOP思想的技术实现中,也只支持方法类型的连接点。
Pointcut(切入点)它指的是那些已经把增强代码加入到业务主线进来之后的连接点。由上图中,我们看出表现层transfer方法就只是连接点,因为判断访问权限的功能并没有对其增强。
Aspect(切面)它指定是增强的代码所关注的方面,把这些相关的增强代码定义到一个类中,这个类就是切面类。例如,事务切面,它里面定义的方法就是和事务相关的,像开启事务,提交事务,回滚事务等等,不会定义其他与事务无关的方法。我们前面的案例中TrasnactionManager就是一个切面。
Advice(通知/增强)它指的是切面类中用于提供增强功能的方法。并且不同的方法增强的时机是不一样的。比如,开启事务肯定要在业务方法执行之前执行;提交事务要在业务方法正常执行之后执行,而回滚事务要在业务方法执行产生异常之后执行等等。那么这些就是通知的类型。其分类有:前置通知 后置通知 异常通知 最终通知 环绕通知。
Target(目标对象)它指的是代理的目标对象。即被代理对象。
Proxy(代理)它指的是一个类被AOP织入增强后,产生的代理类。即代理对象。
Weaving(织入)它指的是把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。
Introduction(引介)它指的是在不修改类代码的前提下, 运行期为目标对象动态地添加一些方法或字段。

⚫ Joinpoint(连接点):就是方法

⚫ Pointcut(切入点):就是挖掉共性功能的方法

⚫ Advice(通知):就是共性功能,最终以一个方法的形式呈现

⚫ Aspect(切面):就是共性功能与挖的位置的对应关系

⚫ Target(目标对象):就是挖掉功能的方法对应的类产生的对象,这种对象是无法直接完成最终工作的

⚫ Weaving(织入):就是将挖掉的功能回填的动态过程

⚫ Proxy(代理):目标对象无法直接完成工作,需要对其进行功能回填,通过创建原始对象的代理对象实现

⚫ Introduction(引入/引介) :就是对原始对象无中生有的添加成员变量或成员方法

AOP开发过程

⚫ 开发阶段(开发者完成)

​ ◆ 正常的制作程序

​ ◆ 将非共性功能开发到对应的目标对象类中,并制作成切入点方法

​ ◆ 将共性功能独立开发出来,制作成通知

​ ◆ 在配置文件中,声明切入点

​ ◆ 在配置文件中,声明切入点与通知间的关系(含通知类型),即切面

⚫ 运行阶段(AOP完成)

​ ◆ Spring容器加载配置文件,监控所有配置的切入点方法的执行

​ ◆ 当监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置将通知对应的功能织入,完成完整的代码逻辑并运行

AOP入门案例

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
    </dependencies>

Service

public interface Service {
    void save();
    void save1();
    void save2();
    void save3();
}

ServiceImpl

public class ServiceImpl implements Service {
    @Override
    public void save() {
        System.out.println("hello");
    }
    @Override
    public void save1() {
        System.out.println("hello");
    }
    @Override
    public void save2() {
        System.out.println("hello");
    }
    @Override
    public void save3() {
        System.out.println("hello");
    }
}

AOPAdvice

public class AOPAdvice {
    public void printTime(){
        System.out.println(System.currentTimeMillis());
    }
}

App

public class App {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        Service service = (Service) ctx.getBean("service");
        service.save();
        service.save1();
        service.save2();
        service.save3();
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: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/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="service" class="com.itheima.service.impl.ServiceImpl"/>

    <bean id="advice" class="com.itheima.aop.AOPAdvice"/>

    <aop:config>
        <aop:pointcut id="pt" expression="execution(* *..*(..))"/>
        <aop:aspect ref="advice">
            <aop:before method="printTime" pointcut-ref="pt"/>
        </aop:aspect>
    </aop:config>
</beans>

AspectJ

⚫ Aspect(切面)用于描述切入点与通知间的关系,是AOP编程中的一个概念

⚫ AspectJ是基于java语言对Aspect的实现

AOP配置

⚫ 名称:aop:config

⚫ 类型:标签

⚫ 归属:beans标签

⚫ 作用:设置AOP

⚫ 格式:

<beans> 

<aop:config>……</aop:config> 

<aop:config>……</aop:config> 

</beans> 

⚫ 说明:一个beans标签中可以配置多个aop:config标签

⚫ 名称:aop:aspect

⚫ 类型:标签

⚫ 归属:aop:config标签

⚫ 作用:设置具体的AOP通知对应的切入点

⚫ 格式:

<aop:config> 

<aop:aspect ref="beanId">……</aop:aspect> 

<aop:aspect ref="beanId">……</aop:aspect> 

</aop:config*> 

⚫ 说明:

​ 一个aop:config标签中可以配置多个aop:aspect标签

⚫ 基本属性:

​ ◆ ref :通知所在的bean的id

⚫ 名称:aop:pointcut

⚫ 类型:标签

⚫ 归属:aop:config标签、aop:aspect标签

⚫ 作用:设置切入点

⚫ 格式:

<aop:config> 

<aop:pointcut id="pointcutId" expression="……"/> 

<aop:aspect> 

<aop:pointcut id="pointcutId" expression="……"/> 

</aop:aspect> 

</aop:config> 

⚫ 说明:

​ 一个aop:config标签中可以配置多个aop:pointcut标签,且该标签可以配置在aop:aspect标签内

⚫ 基本属性:

​ ◆ id :识别切入点的名称

​ ◆ expression :切入点表达式

切入点表达式的组成

⚫ 切入点描述的是某个方法

⚫ 切入点表达式是一个快速匹配方法描述的通配格式,类似于正则表达式

关键字(访问修饰符 返回值 包名.类名.方法名(参数)异常名) 

​ ◆ 关键字:描述表达式的匹配模式(参看关键字列表)

​ ◆ 访问修饰符:方法的访问控制权限修饰符(public 可以省略)

​ ◆ 类名:方法所在的类(此处可以配置接口名称)

​ ◆ 异常:方法定义中指定抛出的异常

⚫ 范例:

execution(public User com.itheima.service.UserService.findById(int))
切入点表达式——范例
execution(* *(..))
execution(* *..*(..))
execution(* *..*.*(..))
execution(public * *..*.*(..))
execution(public int *..*.*(..))
execution(public void *..*.*(..))
execution(public void com..*.*(..)) 
execution(public void com..service.*.*(..))
execution(public void com.itheima.service.*.*(..))
execution(public void com.itheima.service.User*.*(..))
execution(public void com.itheima.service.*Service.*(..))
execution(public void com.itheima.service.UserService.*(..))
execution(public User com.itheima.service.UserService.find*(..))
execution(public User com.itheima.service.UserService.*Id(..))
execution(public User com.itheima.service.UserService.findById(..))
execution(public User com.itheima.service.UserService.findById(int))
execution(public User com.itheima.service.UserService.findById(int,int))
execution(public User com.itheima.service.UserService.findById(int,*))
execution(public User com.itheima.service.UserService.findById(*,int))
execution(public User com.itheima.service.UserService.findById())
execution(List com.itheima.service.*Service+.findAll(..))

切入点配置经验

⚫ 企业开发命名规范严格遵循规范文档进行

⚫ 先为方法配置局部切入点

⚫ 再抽取类中公共切入点

⚫ 最后抽取全局切入点

⚫ 代码走查过程中检测切入点是否存在越界性包含

⚫ 代码走查过程中检测切入点是否存在非包含性进驻

⚫ 设定AOP执行检测程序,在单元测试中监控通知被执行次数与预计次数是否匹配

⚫ 设定完毕的切入点如果发生调整务必进行回归测试

(以上规则适用于XML配置格式)

通知类型

⚫ AOP的通知类型共5种

​ ◆ 前置通知:原始方法执行前执行,如果通知中抛出异常,阻止原始方法运行

​ 应用:数据校验

​ ◆ 后置通知:原始方法执行后执行,无论原始方法中是否出现异常,都将执行通知

​ 应用:现场清理

​ ◆ 返回后通知:原始方法正常执行完毕并返回结果后执行,如果原始方法中抛出异常,无法执行

​ 应用:返回值相关数据处理

​ ◆ 抛出异常后通知:原始方法抛出异常后执行,如果原始方法没有抛出异常,无法执行

​ 应用:对原始方法中出现的异常信息进行处理

​ ◆ 环绕通知:在原始方法执行前后均有对应执行执行,还可以阻止原始方法的执行

​ 应用:十分强大,可以做任何事情

通知类型

1.before

⚫ 名称:aop:before

⚫ 类型:标签

⚫ 归属:aop:aspect标签

⚫ 作用:设置前置通知

⚫ 格式:

<aop:aspect ref="adviceId"> 

<aop:before method="methodName" pointcut="……"/> 

</aop:aspect> 

⚫ 说明:一个aop:aspect标签中可以配置多个aop:before标签

⚫ 基本属性:

◆ method :在通知类中设置当前通知类别对应的方法

◆ pointcut :设置当前通知对应的切入点表达式,与pointcut-ref属性冲突

◆ pointcut-ref :设置当前通知对应的切入点id,与pointcut属性冲突

2.after

⚫ 名称:aop:after

⚫ 类型:标签

⚫ 归属:aop:aspect标签

⚫ 作用:设置后置通知

⚫ 格式:

<aop:aspect ref="adviceId"> 

<aop:after method="methodName" pointcut="……"/> 

</aop:aspect> 

⚫ 说明:一个aop:aspect标签中可以配置多个aop:after标签

⚫ 基本属性:

◆ method :在通知类中设置当前通知类别对应的方法

◆ pointcut :设置当前通知对应的切入点表达式,与pointcut-ref属性冲突

◆ pointcut-ref :设置当前通知对应的切入点id,与pointcut属性冲突

3.after-returning

⚫ 名称:aop:after-returning

⚫ 类型:标签

⚫ 归属:aop:aspect标签

⚫ 作用:设置返回后通知

⚫ 格式:

<aop:aspect ref="adviceId"> 

<aop:after-returning method="methodName" pointcut="……"/> 

</aop:aspect> 

⚫ 说明:一个aop:aspect标签中可以配置多个aop:after-returning标签

⚫ 基本属性:

◆ method :在通知类中设置当前通知类别对应的方法

◆ pointcut :设置当前通知对应的切入点表达式,与pointcut-ref属性冲突

◆ pointcut-ref :设置当前通知对应的切入点id,与pointcut属性冲突

4.after-throwing

⚫ 名称:aop:after-throwing

⚫ 类型:标签

⚫ 归属:aop:aspect标签

⚫ 作用:设置抛出异常后通知

⚫ 格式:

<aop:aspect ref="adviceId"> 

<aop:after-throwing method="methodName" pointcut="……"/> 

</aop:aspect> 

⚫ 说明:一个aop:aspect标签中可以配置多个aop:after-throwing标签

⚫ 基本属性:

◆ method :在通知类中设置当前通知类别对应的方法

◆ pointcut :设置当前通知对应的切入点表达式,与pointcut-ref属性冲突

◆ pointcut-ref :设置当前通知对应的切入点id,与pointcut属性冲突

5.around

⚫ 名称:aop:around

⚫ 类型:标签

⚫ 归属:aop:aspect标签

⚫ 作用:设置环绕通知

⚫ 格式:

<aop:aspect ref="adviceId"> 

<aop:around method="methodName" pointcut="……"/> 

</aop:aspect> 

⚫ 说明:一个aop:aspect标签中可以配置多个aop:around标签

⚫ 基本属性:

◆ method :在通知类中设置当前通知类别对应的方法

◆ pointcut :设置当前通知对应的切入点表达式,与pointcut-ref属性冲突

◆ pointcut-ref :设置当前通知对应的切入点id,与pointcut属性冲突

⚫ 环绕通知是在原始方法的前后添加功能,在环绕通知中,存在对原始方法的显式调用

public Object around(ProceedingJoinPoint pjp) throws Throwable { 
	Object ret = pjp.proceed(); 
	return ret; 
} 

⚫ 环绕通知方法相关说明:

◆ 方法须设定Object类型的返回值,否则会拦截原始方法的返回。如果原始方法返回值类型为

void,通知方法也可以设定返回值类型为void,最终返回null

◆ 方法需在第一个参数位置设定ProceedingJoinPoint对象,通过该对象调用proceed()方法,实

现对原始方法的调用。如省略该参数,原始方法将无法执行

◆ 使用proceed()方法调用原始方法时,因无法预知原始方法运行过程中是否会出现异常,强制抛

出Throwable对象,封装原始方法中可能出现的异常信息

通知顺序

⚫ 当同一个切入点配置了多个通知时,通知会存在运行的先后顺序,该顺序以通知配置的顺序为准

通知获取参数数据

⚫ 设定通知方法第一个参数为JoinPoint,通过该对象调用getArgs()方法,获取原始方法运行的参数数组

public void before(JoinPoint jp) throws Throwable { 

Object[] args = jp.getArgs(); 

} 

⚫ 所有的通知均可以获取参数

通知获取返回值数据

1.适用于返回后通知(after-returning)

⚫ 设定返回值变量名

⚫ 原始方法

public int save() { 

System.out.println("user service running..."); 

return 100; 

} 

⚫ AOP配置

<aop:aspect ref="myAdvice"> 

<aop:pointcut id="pt3" expression="execution(* *(..)) "/> 

<aop:after-returning method="afterReturning" pointcut-ref="pt3" returning="ret"/> 

</aop:aspect> 

⚫ 通知类

public void afterReturning(Object ret) { 

System.out.println(ret); 

} 
2.适用于环绕通知(around)

⚫ 原始方法

public int save() { 

System.out.println("user service running..."); 

return 100; 

} 

⚫ AOP配置

<aop:aspect ref="myAdvice"> 

<aop:pointcut id="pt2" expression="execution(* *(..)) "/> 

<aop:around method="around" pointcut-ref="pt2" /> 

</aop:aspect> 

⚫ 通知类

public Object around(ProceedingJoinPoint pjp) throws Throwable { 

Object ret = pjp.proceed(); 

return ret; 

} 

通知获取异常数据

1.适用于环绕通知(around)

⚫ 在通知类的方法中调用原始方法捕获异常

⚫ 原始方法

public void save() {
	System.out.println("user service running...");
	int i = 1/0; 
}

⚫ AOP配置

<aop:aspect ref="myAdvice"> 
	<aop:pointcut id="pt4" expression="execution(* *(..)) "/>
	<aop:around method="around" pointcut-ref="pt4" />
</aop:aspect>

⚫ 通知类

public Object around(ProceedingJoinPoint pjp) throws Throwable {
	Object ret = pjp.proceed(); //对此处调用进行try……catch……捕获异常,或抛出异常
	return ret;
}
2.适用于返回后通知(after-throwing)

⚫ 设定异常对象变量名

⚫ 原始方法

public void save() { 

System.out.println("user service running..."); 

int i = 1/0; 

} 

⚫ AOP配置

<aop:aspect ref="myAdvice"> 

<aop:pointcut id="pt4" expression="execution(* *(..)) "/> 

<aop:after-throwing method="afterThrowing" pointcut-ref="pt4" throwing="t"/> 

</aop:aspect> 

⚫ 通知类

public void afterThrowing(Throwable t){ 

System.*out*.println(t.getMessage()); 

} 

AOP注解

1.名称:@Aspect

⚫ 类型:注解

⚫ 位置:类定义上方

⚫ 作用:设置当前类为切面类

⚫ 格式:

@Aspect 

public class AopAdvice { 

} 

⚫ 说明:一个beans标签中可以配置多个aop:config标签

2.名称:@Before

⚫ 类型:注解

⚫ 位置:方法定义上方

⚫ 作用:标注当前方法作为前置通知

⚫ 格式:

@Before("pt()") 

public void before(){ 

} 

⚫ 特殊参数:

◆ 无

3.名称:@After

⚫ 类型:注解

⚫ 位置:方法定义上方

⚫ 作用:标注当前方法作为后置通知

⚫ 格式:

@After("pt()") 

public void after(){ 

} 

⚫ 特殊参数:

◆ 无

4.名称:@AfterReturning

⚫ 类型:注解

⚫ 位置:方法定义上方

⚫ 作用:标注当前方法作为返回后通知

⚫ 格式:

@AfterReturning(value="pt()",returning = "ret") 

public void afterReturning(Object ret) { 

} 

⚫ 特殊参数:

◆ returning :设定使用通知方法参数接收返回值的变量名

5.名称:@AfterThrowing

⚫ 类型:注解

⚫ 位置:方法定义上方

⚫ 作用:标注当前方法作为异常后通知

⚫ 格式:

@AfterThrowing(value="pt()",throwing = "t") 

public void afterThrowing(Throwable t){ 

} 

⚫ 特殊参数:

◆ throwing :设定使用通知方法参数接收原始方法中抛出的异常对象名

6.名称:@Around

⚫ 类型:注解

⚫ 位置:方法定义上方

⚫ 作用:标注当前方法作为环绕通知

⚫ 格式:

@Around("pt()") 

public Object around(ProceedingJoinPoint pjp) throws Throwable { 

Object ret = pjp.proceed(); 

return ret; 

} 

⚫ 特殊参数:

◆ 无

AOP注解开发通知执行顺序控制和企业开发经验

⚫ AOP使用XML配置情况下,通知的执行顺序由配置顺序决定,在注解情况下由于不存在配置顺序的概念的概念,参照通知所配置的方法名字符串对应的编码值顺序,可以简单理解为字母排序

​ ◆ 同一个通知类中,相同通知类型以方法名排序为准

​ ◆ 不同通知类中,以类名排序为准

​ ◆ 使用@Order注解通过变更bean的加载顺序改变通知的加载顺序

⚫ 企业开发经验

​ ◆ 通知方法名由3部分组成,分别是前缀、顺序编码、功能描述

​ ◆ 前缀为固定字符串,例如baidu、itheima等,无实际意义

​ ◆ 顺序编码为6位以内的整数,通常3位即可,不足位补0

​ ◆ 功能描述为该方法对应的实际通知功能,例如exception、strLenCheck

​ ◆ 控制通知执行顺序使用顺序编码控制,使用时做一定空间预留

​ ◼ 003使用,006使用,预留001、002、004、005、007、008

​ ◼ 使用时从中段开始使用,方便后期做前置追加或后置追加

​ ◼ 最终顺序以运行顺序为准,以测试结果为准,不以设定规则为准

AOP注解驱动

⚫ 名称:@EnableAspectJAutoProxy

⚫ 类型:注解

⚫ 位置:Spring注解配置类定义上方

⚫ 作用:设置当前类开启AOP注解驱动的支持,加载AOP注解

⚫ 格式:

@Configuration 

@ComponentScan("com.itheima") 

@EnableAspectJAutoProxy 

public class SpringConfig { 

}

静态代理

public class UserServiceDecorator implements UserService{
	private UserService userService;
	public UserServiceDecorator(UserService userService) {
		this.userService = userService;
	}
	public void save() {
		//原始调用
		userService.save();
		//增强功能(后置)
		System.out.println("刮大白");
	}
}

动态代理JDK Proxy

public class UserServiceJDKProxy { 
public UserService createUserServiceJDKProxy(final UserService userService){ 
//获取被代理对象的类加载器 
ClassLoader classLoader = userService.getClass().getClassLoader(); 
//获取被代理对象实现的接口
Class[] classes = userService.getClass().getInterfaces(); 
//对原始方法执行进行拦截并增强
InvocationHandler ih = new InvocationHandler() { 
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
//前置增强内容
Object ret = method.invoke(userService, args); 
//后置增强内容 
System.out.println("刮大白2"); 
return ret; 
} 
}; 
//使用原始被代理对象创建新的代理对象 
UserService proxy = (UserService) Proxy.*newProxyInstance*(classLoader,classes,ih); 
return proxy; 
} 
}

动态代理——CGLIB

public class UserServiceImplCglibProxy {
public static UserServiceImpl createUserServiceCglibProxy(Class clazz){
//创建Enhancer对象(可以理解为内存中动态创建了一个类的字节码)
Enhancer enhancer = new Enhancer();
//设置Enhancer对象的父类是指定类型UserServerImpl
enhancer.setSuperclass(clazz);①
Callback cb = new MethodInterceptor() {public Object intercept(Object o, Method m, Object[] a, MethodProxy mp) throws Throwable {
Object ret = mp.invokeSuper(o, a);if(m.getName().equals("save")) {
System.out.println("刮大白");
}
return ret;
}
};
//设置回调方法
enhancer.setCallback(cb);//使用Enhancer对象创建对应的对象
return (UserServiceImpl)enhancer.create();
} }

代理模式的选择

⚫ Spirng可以通过配置的形式控制使用的代理形式,默认使用jdkproxy,通过配置可以修改为使用cglib

◆ XML配置

<!--XMP配置AOP-->
<aop:config proxy-target-class="false"> 
</aop:config> 

◆ XML注解支持

<!--注解配置AOP-->
<aop:aspectj-autoproxy proxy-target-class="false"/> 

◆ 注解驱动

//注解驱动
@EnableAspectJAutoProxy(proxyTargetClass = true)

Spring管理事务

声明式事务

<!--配置事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置通知类-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" read-only="false"/>
            <tx:method name="find*" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="pt" expression="execution(* com.itheima..*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    </aop:config>
tx配置
1.名称:tx:advice

⚫ 类型:标签

⚫ 归属:beans标签

⚫ 作用:专用于声明事务通知

⚫ 格式:

<beans> 

<tx:advice id="txAdvice" transaction-manager="txManager"> 

</tx:advice> 

</beans> 

⚫ 基本属性:

◆ id :用于配置aop时指定通知器的id

◆ transaction-manager :指定事务管理器bean

2.名称:tx:attributes

⚫ 类型:标签

⚫ 归属:tx:advice标签

⚫ 作用:定义通知属性

⚫ 格式:

<tx:advice id="txAdvice" transaction-manager="txManager"> 

<tx:attributes> 

</tx:attributes> 

</tx:advice> 

⚫ 基本属性:

◆ 无

3.名称:tx:method

⚫ 类型:标签

⚫ 归属:tx:attribute标签

⚫ 作用:设置具体的事务属性

⚫ 格式:

<tx:attributes> 

<tx:method name="*" read-only="false" /> 

<tx:method name="get*" read-only="true" /> 

</tx:attributes> 

⚫ 说明:

通常事务属性会配置多个,包含1个读写的全事务属性,1个只读的查询类事务属性

⚫ method属性

<tx:method 
name="*"  待添加事务的方法名表达式(支持*号通配符),例如get* 、* 、……
read-only="false"  设置事务的读写属性,true为只读,false为读写
timeout="-1"  设置事务超时时长,单位秒
isolation="DEFAULT"  设置事务隔离级别,该隔离级设定是基于Spring的设定,非数据库端
no-rollback-for=""  设置事务中不回滚的异常,多个异常间使用,分割
rollback-for=""  设置事务中必回滚的异常,多个异常间使用,分割
propagation="REQUIRED"  设置事务的传播行为
/>

声明式事务(注解)

1.名称:@Transactional

⚫ 类型:方法注解,类注解,接口注解

⚫ 位置:方法定义上方,类定义上方,接口定义上方

⚫ 作用:设置当前类/接口中所有方法或具体方法开启事务,并指定相关事务属性

⚫ 范例:

@Transactional( 

readOnly = false, 

timeout = -1, 

isolation = Isolation.*DEFAULT*, 

rollbackFor = {ArithmeticException.class, IOException.class}, 

noRollbackFor = {}, 

propagation = Propagation.*REQUIRES_NEW* 

)
2.名称:tx:annotation-driven

⚫ 类型:标签

⚫ 归属:beans标签

⚫ 作用:开启事务注解驱动,并指定对应的事务管理器

⚫ 范例:

<tx:annotation-driven transaction-manager="txManager"/>
3.名称:tx:annotation-driven

⚫ 类型:标签

⚫ 归属:beans标签

⚫ 作用:开启事务注解驱动,并指定对应的事务管理器

⚫ 范例:

<tx:annotation-driven transaction-manager="txManager"/>

事务传播行为

在这里插入图片描述

  • 需要
    • REQUIREW(需要)
    • REQUIREW_NEW(需要新的事务)
  • 支持
    • SUPPORTS, 支持
    • NOT_SUPPORTED, 不支持
  • 强制
    • MANDATORY, 必须要有事务
    • NEVER, 必须不能有

Spring整合redisTemplate

@PropertySource("redis.properties")
public class RedisConfig {

    @Value("${redis.host}")
    private String hostName;

    @Value("${redis.port}")
    private Integer port;

//    @Value("${redis.password}")
//    private String password;

    @Value("${redis.maxActive}")
    private Integer maxActive;
    @Value("${redis.minIdle}")
    private Integer minIdle;
    @Value("${redis.maxIdle}")
    private Integer maxIdle;
    @Value("${redis.maxWait}")
    private Integer maxWait;


    /
     *
     * @param redisConnectionFactory 链接工厂
     * @return
     */
    @Bean
    //配置RedisTemplate
    public RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory){
        //1.创建对象
        RedisTemplate redisTemplate = new RedisTemplate();
        //2.设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //3.设置redis生成的key的序列化器,对key编码进行处理
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        //4.返回
        return redisTemplate;
    }

    /
     *
     * @param redisStandaloneConfiguration 链接信息
     * @param genericObjectPoolConfig 连接池信息
     * @return RedisConnectionFactory 链接工厂
     */
    @Bean
    //配置Redis连接工厂
    public RedisConnectionFactory createRedisConnectionFactory(RedisStandaloneConfiguration redisStandaloneConfiguration,
                                                               GenericObjectPoolConfig genericObjectPoolConfig){
        //1.创建配置构建器,它是基于池的思想管理Jedis连接的
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder builder =
                (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder)
                        JedisClientConfiguration.builder();
        //2.设置池的配置信息对象
        builder.poolConfig(genericObjectPoolConfig);
        //3.创建Jedis连接工厂
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration,builder.build());
        //4.返回
        return jedisConnectionFactory;
    }

    /
     *
     * @return 保存连接池信息
     */
    @Bean
    //配置spring提供的Redis连接池信息
    public GenericObjectPoolConfig createGenericObjectPoolConfig(){
        //1.创建Jedis连接池的配置对象
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        //2.设置连接池信息
        genericObjectPoolConfig.setMaxTotal(maxActive);
        genericObjectPoolConfig.setMinIdle(minIdle);
        genericObjectPoolConfig.setMaxIdle(maxIdle);
        genericObjectPoolConfig.setMaxWaitMillis(maxWait);
        //3.返回
        return genericObjectPoolConfig;
    }


    /
     *
     * @return 保存的链接信息
     */
    @Bean
    //配置Redis标准连接配置对象 redis单点配置
    public RedisStandaloneConfiguration createRedisStandaloneConfiguration(){
        //1.创建Redis服务器配置信息对象
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        //2.设置Redis服务器地址,端口和密码(如果有密码的话)
        redisStandaloneConfiguration.setHostName(hostName);
        redisStandaloneConfiguration.setPort(port);
//        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
        //3.返回
        return redisStandaloneConfiguration;
    }

}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值