程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Spring核心API介绍

发布于2021-05-29 20:32     阅读(1201)     评论(0)     点赞(5)     收藏(1)


 

Spring核心API介绍

BeanFactory

org.springframework.beans.factory

BeanFactory是用于访问Spring Bean容器的根接口,典型的工厂模式,用于生产Bean的一个Bean工厂,其提供了生产Bean所需的最基本规则。

BeanFactory的所有方法:

0

0

 

BeanDefinition

功能

BeanDefinition是bean在spring中的描述,有了BeanDefinition我们就可以创建Bean,BeanDefinition是Bean在spring中的定义形态 接下来我们看看BeanDefinition的相关接口与类.

方法

  • String: getBeanClassName: 返回当前bean definition定义的类名
  • ConstructorArgumentValues: getConstructorArgumentValues:返回bean的构造函数参数
  • String[]: getDependsOn:返回当前bean所依赖的其他bean的名称
  • String: getFactoryBeanName: 返回factory bean的名称
  • String: getFactoryMethodName: 返回工厂方法的名称
  • BeanDefinition: getOriginatingBeanDefinition: 返回原始的BeanDefinition,如果不存在返回null
  • String: getParentName: 返回当前bean definition的父definition的名字
  • MutablePropertyValues: getPropertyValues: 返回一个用于新的bean实例上的属性值
  • String: getScope: 返回当前bean的目标范围
  • boolean: isAbstract: 当前bean是否是abstract,意味着不能被实例化
  • boolean: isLazyInit: bean是否是延迟初始化
  • boolean: isPrimary: bean是否为自动装配的主要候选bean
  • boolean: isPrototype: bean是否是多实例
  • boolean: isSingleton: bean是否是单例
  • void: setAutowiredCandidate(boolean): 设置bean是否对其他bean是自动装配的候选bean
  • void: setBeanClassName(String): 指定bean definition的类名
  • void: setDependsOn(String ...): 设置当前bean初始化所依赖的beans的名称
  • void: setFactoryBeanName(String): 如果factory bean的名称
  • void: setFactoryMethodName(String): 设置工厂的方法名
  • void: setLazyInit(boolean lazyInit): 设置是否延迟初始化
  • void: setParentName(String): 设置父definition的名称
  • void: setPrimary(boolean): 设置是否主要的候选bean
  • void: setScope(String): 设置bean的范围,如:单例,多实例

定义

  • BeanDefinition接口: 顶级基础接口,用来描述Bean,里面存放Bean元数据,比如Bean类名、scope、属性、构造函数参数列表、依赖的bean、是否是单例类、是否是懒加载等一些列信息。

向上

0

  • BeanMetadataElement接口:BeanDefinition元数据,返回该Bean的来源
  • AttributeAccessor接口:提供对BeanDefinition属性操作能力,

向下

0

  • AbstractBeanDefinition类:抽象类统一实现了BeanDefinition定义的一部分操作,可以说是定义了BeanDefinition很多默认的属性。 正是在AbstractBeanDefinition基础上, Spring衍生出了一些列BeaDefinition。

这里我们可以关注下重写的equals(),hashcode(), toString()方法

此外initMethodName属性,destroyMethodName 属性, 这两个属性bean的生命周期有关,此处只提一句,后续讲解。

接下来。我们看看从AbstractBeanDefinition上衍生出来的几个类

  • RootBeanDefinition: 代表一个xml,java Config来的BeanDefinition
  • ChildBeanDefinition: 从Spring2.5开始,ChildBeanDefinition已经不再使用,取而代之的是GenericBeanDefinition。
  • GenericBeanDefinition: spring2.5后注册bean首选的是GenericBeanDefinition。GenericBeanDefinition允许动态的设置父bean.GenericBeanDefinition可以作为RootBeanDefinition与ChildBeanDefinition的替代品。
  • AnnotatedBeanDefinition接口: 表示注解类型BeanDefinition。有两个重要的属性,AnnotationMetadata,MethodMetadata分别表示BeanDefinition的注解元信息和方法元信息 实现了此接口的BeanDefinition可以获取到注解元数据和方法元数据。
  • AnnotatedGenericBeanDefinition类: 表示@Configuration注解注释的BeanDefinition类
  • ScannedGenericBeanDefinition类: 表示@Component、@Service、@Controller等注解注释的Bean类

操作

动作也可分为两种: 一种是针对自身的操作: 自提提供给外部的可以操作其本身的动作 另一种是外部对BeanDefinition的操作

  • BeanDefinitionRegistry接口:具有增,查,删BeanDefinition的能力。一次只能注册一个BeanDefinition.

实现类SimpleBeanDefinitionRegistry,DefaultListableBeanFactory,GenericApplicationContext等 一般实现类里都都有一个 private final Map beanDefinitionMap = new ConcurrentHashMap()来存储BeanDefinition. 

0

  • BeanDefinitionReader接口: 既可以使用BeanDefinitionRegistry构造。也可以通过loadBeanDefinitions把配置加载为多个BeanDefinition并注册到BeanDefinitionRegistry中。 可以说是高效版本的BeanDefinitionRegistry. 实现类有 XmlBeanDefinitionReader从xml中读取BeanDefinition; PropertiesBeanDefinitionReader从Properties文件读取BeanDefinition
  • AnnotatedBeanDefinitionReader类 对带有注解的BeanDefinition进行注册
  • ClassPathBeanDefinitionScanner类: 可以扫描到@Component @Repository @Service @Controller 的BeanDefinition注册到容器中。

其他形态

  • BeanDefinitionHolder: BeanDefinition包装类。

Bean

Bean是我们需要的对象,是我们从spring内得到的结果,也就是对象实例

定义

从定义层面看.Bean其实就是我们需要的对象.

操作

我们来看看Bean在spring有哪些操作相关的接口或类。

  • SingletonBeanRegistry接口:与BeanDefinition的注册相应的。Bean的操作也有一个类似的接口来操作Bean.SingletonBeanRegistry接口提供了对Bean的注册,获取,存在性判断等功能。
  • InitializingBean:对于实现 InitializingBean的Bean,它将执行 afterPropertiesSet(); 在所有的 bean 属性被设置之后。
  • InstantiationStrategy:提供 Bean实例化的策略接口,
  • DisposableBean:对于 实现了DisposableBean的Bean ,它将运行 destroy()在 Spring 容器释放该 bean 之后
  • FactoryBean: 生产Bean的Bean.

其他形态

  • BeanWrapper: 对Bean的包装.BeanWrapper可以看作是一个从 BeanDefinition 到 Bean 过程中间的产物,可以称为”低级 bean“,在一般情况下,我们不会在实际项目中用到它。BeanWrapper 是 Spring 框架中重要的组件类,它就相当于一个代理类,Spring 委托 BeanWrapper 完成 Bean 属性的填充工作。在 bean 实例被 InstantiatioonStrategy 创建出来后,Spring 容器会将 Bean 实例通过 BeanWrapper 包裹起来,是通过 BeanWrapper.setWrappedInstance() 完成的

总结:

BeanDefinition是物料,Bean是成品,理解BeanDefinition与Bean的关系是理解spring的基础。

 

AOP

Pointcut家族

它是Spring AOP对切点的一个顶层首相,非常的重要。

首先得看看这个顶级接口抽象的图谱:

0

这里面有一个非常重要得子接口:ExpressionPointcut,它是用于解析String类型的切点表达式的接口(这也是我们使用得最最最多的)

Pointcut接口分析

**主要负责对系统的相应的Joinpoint进行捕捉,对系统中所有的对象进行Joinpoint所定义的规则进行匹配。**提供了一个TruePointcut实例,当Pointcut为TruePointcut类型时,则会忽略所有的匹配条件,永远返回true

显然可以看出,这个接口和ClassFilterMethodMatcher有关系

  1. public interface Pointcut {
  2. ClassFilter getClassFilter();
  3. MethodMatcher getMethodMatcher();
  4. /**
  5. * Canonical Pointcut instance that always matches.
  6. * 意思是:用于匹配上的一个实例(意思是永远返回true嘛)
  7. */
  8. Pointcut TRUE = TruePointcut.INSTANCE;
  9. }

 

ClassFilter与MethodMatcher分别用于在不同的级别上限定Joinpoint的匹配范围,满足不同粒度的匹配

ClassFilter限定在类级别上,MethodMatcher限定在方法级别上

SpringAop主要支持在方法级别上的匹配,所以对类级别的匹配支持相对简单一些

ClassFilter

  1. @FunctionalInterface
  2. public interface ClassFilter {
  3. // true表示能够匹配。那就会进行织入的操作
  4. boolean matches(Class<?> clazz);
  5. // 常量 会匹配所有的类 TrueClassFilter不是public得class,所以只是Spring内部自己使用的
  6. ClassFilter TRUE = TrueClassFilter.INSTANCE;
  7. }

Spring给他的实现类也比较多,如下:

0

RootClassFilter

  1. public class RootClassFilter implements ClassFilter, Serializable {
  2. private Class<?> clazz;
  3. public RootClassFilter(Class<?> clazz) {
  4. this.clazz = clazz;
  5. }
  6. // 显然,传进来的candidate必须是clazz的子类才行
  7. @Override
  8. public boolean matches(Class<?> candidate) {
  9. return clazz.isAssignableFrom(candidate);
  10. }
  11. }

AnnotationClassFilter

  1. public class AnnotationClassFilter implements ClassFilter {
  2. ...
  3. public AnnotationClassFilter(Class<? extends Annotation> annotationType) {
  4. // 默认情况下checkInherited给的false:不去看它继承过来的注解
  5. this(annotationType, false);
  6. }
  7. // checkInherited true:表示继承过来得注解也算
  8. public AnnotationClassFilter(Class<? extends Annotation> annotationType, boolean checkInherited) {
  9. Assert.notNull(annotationType, "Annotation type must not be null");
  10. this.annotationType = annotationType;
  11. this.checkInherited = checkInherited;
  12. }
  13. ...
  14. @Override
  15. public boolean matches(Class<?> clazz) {
  16. return (this.checkInherited ?
  17. // 继承的注解也会找出来
  18. (AnnotationUtils.findAnnotation(clazz, this.annotationType) != null) :
  19. // 只会看自己本类的注解
  20. clazz.isAnnotationPresent(this.annotationType));
  21. }
  22. }

AspectJExpressionPointcut

它既是个Pointcut,它也是个ClassFilter,下面会详细分析本类

MethodMatcher

  1. public interface MethodMatcher {
  2. // 这个称为静态匹配:在匹配条件不是太严格时使用,可以满足大部分场景的使用
  3. boolean matches(Method method, @Nullable Class<?> targetClass);
  4. // 这个称为动态匹配(运行时匹配): 它是严格的匹配。在运行时动态的对参数的类型进行匹配
  5. boolean matches(Method method, @Nullable Class<?> targetClass, Object... args);
  6. //两个方法的分界线就是boolean isRuntime()方法,步骤如下
  7. // 1、先调用静态匹配,若返回true。此时就会继续去检查isRuntime()的返回值
  8. // 2、若isRuntime()还返回true,那就继续调用动态匹配
  9. // (若静态匹配都匹配上,动态匹配那铁定更匹配不上得~~~~)
  10. // 是否需要执行动态匹配
  11. boolean isRuntime();
  12. MethodMatcher TRUE = TrueMethodMatcher.INSTANCE;
  13. }

应用场景:比如需要统计用户登录次数时,那么登录传入的参数就是可以忽略的,则静态匹配就足够了

但是若要在登陆时对用户账号执行特殊的操作**(如赋予特殊的操作权限)**,就需要对参数进行一个类似于检验的操作,因此需要动态匹配

0

它有两个非常重要的抽象实现:StaticMethodMatcherDynamicMethodMatcher

StaticMethodMatcher 静态匹配

  1. public abstract class StaticMethodMatcher implements MethodMatcher {
  2. // 永远返回false表示只会去静态匹配
  3. @Override
  4. public final boolean isRuntime() {
  5. return false;
  6. }
  7. // 三参数matches抛出异常,使其不被调用
  8. @Override
  9. public final boolean matches(Method method, @Nullable Class<?> targetClass, Object... args) {
  10. // should never be invoked because isRuntime() returns false
  11. throw new UnsupportedOperationException("Illegal MethodMatcher usage");
  12. }
  13. }

作用:它表示不会考虑具体 方法参数。因为不用每次都检查参数,那么对于同样的类型的方法匹配结果,就可以在框架内部缓存以提高性能。比如常用的实现类:AnnotationMethodMatcher

DynamicMethodMatcher 动态匹配

  1. public abstract class DynamicMethodMatcher implements MethodMatcher {
  2. // 永远返回true
  3. @Override
  4. public final boolean isRuntime() {
  5. return true;
  6. }
  7. // 永远返回true,去匹配动态匹配的方法即可
  8. @Override
  9. public boolean matches(Method method, @Nullable Class<?> targetClass) {
  10. return true;
  11. }
  12. }

说明:因为每次都要对方法参数进行检查,无法对匹配结果进行缓存,所以,匹配效率相对 StatisMethodMatcher 来说要差,但匹配度更高。(实际使用得其实较少)

JdkRegexpMethodPointcut:基于正则的Pointcut

Spring官方为我们提供了一个基于正则表达式来匹配方法名的Pointcut,JdkRegexpMethodPointcut

0

它提供了最重要的4个属性(patternsexcludedPatterns来自于父类AbstractRegexpMethodPointcut):

这里昂个属性来自于父类,相对来说就是比较简单的匹配signatureString(方法的全路径名称)

  • String[] patterns:匹配的正则表达式。如find.*表示所有方法名以find开始的方法
  • String[] excludedPatterns:排除的正则表达式们

下面两个是子类,也就是JdkRegexpMethodPointcut自己提供的属性

  • Pattern[] compiledPatterns:相当于把正则字符串,Pattern.compile()成正则对象
  • Pattern[] compiledExclusionPatterns:同上

都是数组,正则表达式都可以多个哟~~

需要注意的是,这两组含义相同,请不要同时跨组使用,没有意义,没必要深究。

这种切点表达式,在早期Spring中的使用较多,一般这么使用:

  1. <!-- 自己书写的日志切面 -->
  2. <bean id="logBeforeAdvice" class="com.fsx.aop.LogBeforeAdvice" />
  3. <!-- 使用JDK的正则切点~~~~~~ -->
  4. <bean id="regexPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
  5. <property name="patterns">
  6. <list>
  7. <value>find.*</value><!-- 拦截所有方法名以find开始的方法 -->
  8. </list>
  9. </property>
  10. </bean>
  11. <!-- 切面+切点 组合成一个增强器即可~~~~~~ -->
  12. <aop:config>
  13. <aop:advisor advice-ref="logBeforeAdvice" pointcut-ref="regexPointcut"/>
  14. </aop:config>

其实Spring为我们提供了一个简便的Advisor定义,可以方便的让我们同时指定一个JdkRegexpMethodPointcut和其需要对应的Advice,它就是RegexpMethodPointcutAdvisor,这样配置起来非常的方便

  1. <bean id="logBeforeAdvice" class="com.fsx.aop.LogBeforeAdvice" />
  2. <bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
  3. <property name="advice" ref="logBeforeAdvice"/>
  4. <property name="pattern" value="find.*"/>
  5. </bean>

https://note.youdao.com/yws/public/resource/c9bde74fde820328f08b053548d5d3e8/xmlnote/7AFDBA65A2364F4AA73498D0A639FF46/7418

这个举例事基于XML的,之前我们都是这么来用的。那么现在用Java代码的方式也实现一遍(不需要Spring容器):

  1. public static void main(String[] args) {
  2. ProxyFactory factory = new ProxyFactory(new Person());
  3. //声明一个aspectj切点,一张切面
  4. JdkRegexpMethodPointcut cut = new JdkRegexpMethodPointcut();
  5. //cut.setPattern("com.fsx.maintest.Person.run"); //它会拦截Person类下所有run的方法(无法精确到方法签名)
  6. //cut.setPattern(".*run.*");//.号匹配除"\r\n"之外的任何单个字符。*号代表零次或多次匹配前面的字符或子表达式 所以它拦截任意包下任意类的run方法
  7. cut.setPatterns(new String[]{".*run.*", ".*say.*"}); //可以配置多个正则表达 式... sayHi方法也会被拦截
  8. // 声明一个通知(此处使用环绕通知 MethodInterceptor )
  9. Advice advice = (MethodInterceptor) invocation -> {
  10. System.out.println("============>放行前拦截...");
  11. Object obj = invocation.proceed();
  12. System.out.println("============>放行后拦截...");
  13. return obj;
  14. };
  15. //切面=切点+通知
  16. // 它还有个构造函数:DefaultPointcutAdvisor(Advice advice); 用的切面就是Pointcut.TRUE,所以如果你要指定切面,请使用自己指定的构造函数
  17. // Pointcut.TRUE:表示啥都返回true,也就是说这个切面作用于所有的方法上/所有的方法
  18. // addAdvice();方法最终内部都是被包装成一个 `DefaultPointcutAdvisor`,且使用的是Pointcut.TRUE切面,因此需要注意这些区别 相当于new DefaultPointcutAdvisor(Pointcut.TRUE,advice);
  19. Advisor advisor = new DefaultPointcutAdvisor(cut, advice);
  20. factory.addAdvisor(advisor);
  21. Person p = (Person) factory.getProxy();
  22. // 执行方法
  23. p.run();
  24. p.run(10);
  25. p.say();
  26. p.sayHi("Jack");
  27. p.say("Tom", 666);
  28. }
  29. }
  30. class Person {
  31. public int run() {
  32. System.out.println("我在run...");
  33. return 0;
  34. }
  35. public void run(int i) {
  36. System.out.println("我在run...<" + i + ">");
  37. }
  38. public void say() {
  39. System.out.println("我在say...");
  40. }
  41. public void sayHi(String name) {
  42. System.out.println("Hi," + name + ",你好");
  43. }
  44. public int say(String name, int i) {
  45. System.out.println(name + "----" + i);
  46. return 0;
  47. }
  48. }
  49. 输出:
  50. ============>放行前拦截...
  51. 我在run...
  52. ============>放行后拦截...
  53. ============>放行前拦截...
  54. 我在run...<10>
  55. ============>放行后拦截...
  56. ============>放行前拦截...
  57. 我在say...
  58. ============>放行后拦截...
  59. ============>放行前拦截...
  60. Hi,Jack,你好
  61. ============>放行后拦截...
  62. ============>放行前拦截...
  63. Tom----666
  64. ============>放行后拦截...

最后需要注意的是:RegexpMethodPointcutAdvisor没有提供不匹配的正则表达式注入方法,即没有excludedPatterns注入,如果需要该功能请还是使用JdkRegexpMethodPointcut

AspectJExpressionPointcut详细使用和分析

AspectJExpressionPointcut如字面,它和Expression有关,而这个切点表达式,最终还是依赖于AspectJ的jar包去解析的~~~~ Spring在使用@Aspect注解时,会大量的用到它

AspectJExpressionPointcut实现的切点比JdkRegexpMethodPointcut实现切点的好处就是,在设置切点的时候可以用切点语言来更加精确的表示拦截哪个方法。(可以精确到返回参数,参数类型,方法名,当然,也可以模糊匹配)

纯Java方式Demo:

下面我先用一个纯Java的方式的例子,先体验一把:

  1. public static void main(String[] args) {
  2. //String pointcutExpression = "execution( int com.fsx.maintest.Person.run() )"; // 会拦截Person.run()方法
  3. //String pointcutExpression = "args()"; // 所有没有入参的方法会被拦截。 比如:run()会拦截,但是run(int i)不会被拦截
  4. // ... AspectJExpressionPointcut支持的表达式 一共有11种(也就是Spring全部支持的切点表达式类型)
  5. String pointcutExpression = "@annotation(org.springframework.test.context.transaction.AfterTransaction)"; // 拦截上方法标有@AfterTransaction此注解的任意方法们
  6. // =============================================================
  7. ProxyFactory factory = new ProxyFactory(new Person());
  8. //声明一个aspectj切点,一张切面
  9. AspectJExpressionPointcut cut = new AspectJExpressionPointcut();
  10. cut.setExpression(pointcutExpression); // 设置切点表达式
  11. // 声明一个通知(此处使用环绕通知 MethodInterceptor )
  12. Advice advice = (MethodInterceptor) invocation -> {
  13. System.out.println("============>放行前拦截...");
  14. Object obj = invocation.proceed();
  15. System.out.println("============>放行后拦截...");
  16. return obj;
  17. };
  18. //切面=切点+通知
  19. // 它还有个构造函数:DefaultPointcutAdvisor(Advice advice); 用的切面就是Pointcut.TRUE,所以如果你要指定切面,请使用自己指定的构造函数
  20. // Pointcut.TRUE:表示啥都返回true,也就是说这个切面作用于所有的方法上/所有的方法
  21. // addAdvice();方法最终内部都是被包装成一个 `DefaultPointcutAdvisor`,且使用的是Pointcut.TRUE切面,因此需要注意这些区别 相当于new DefaultPointcutAdvisor(Pointcut.TRUE,advice);
  22. Advisor advisor = new DefaultPointcutAdvisor(cut, advice);
  23. factory.addAdvisor(advisor);
  24. Person p = (Person) factory.getProxy();
  25. // 执行方法
  26. p.run();
  27. p.run(10);
  28. p.say();
  29. p.sayHi("Jack");
  30. p.say("Tom", 666);
  31. }
  32. }
  33. class Person {
  34. @AfterTransaction
  35. public int run() {
  36. System.out.println("我在run...");
  37. return 0;
  38. }
  39. public void run(int i) {
  40. System.out.println("我在run...<" + i + ">");
  41. }
  42. public void say() {
  43. System.out.println("我在say...");
  44. }
  45. public void sayHi(String name) {
  46. System.out.println("Hi," + name + ",你好");
  47. }
  48. public int say(String name, int i) {
  49. System.out.println(name + "----" + i);
  50. return 0;
  51. }
  52. }

如上面的图,其实Spring也我们提供了AspectJExpressionPointcutAdvisor来专门处理基于AspectJ的通知+切点的

XML方式

  1. public class Person {
  2. @AfterTransaction
  3. public int run() {
  4. System.out.println("我在run...");
  5. return 0;
  6. }
  7. public void run(int i) {
  8. System.out.println("我在run...<" + i + ">");
  9. }
  10. public void say() {
  11. System.out.println("我在say...");
  12. }
  13. public void sayHi(String name) {
  14. System.out.println("Hi," + name + ",你好");
  15. }
  16. public int say(String name, int i) {
  17. System.out.println(name + "----" + i);
  18. return 0;
  19. }
  20. }
  21. // 相当于准备了一个Advice
  22. public class MyMethodInteceptor implements MethodInterceptor {
  23. @Override
  24. public Object invoke(MethodInvocation invocation) throws Throwable {
  25. System.out.println("============>放行前拦截...");
  26. Object obj = invocation.proceed();
  27. System.out.println("============>放行后拦截...");
  28. return obj;
  29. }
  30. }

书写Spring的xml配置文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <!-- 作为示例,这是需要被切入的目标类 -->
  6. <bean class="com.fsx.bean.Person"/>
  7. <!-- 切面=切点+通知 (采用面向切点语言进行配置切面) 此处为了便捷 直接使用 AspectJExpressionPointcutAdvisor -->
  8. <bean id="advisor" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
  9. <property name="expression"
  10. value="@annotation(org.springframework.test.context.transaction.AfterTransaction)"></property>
  11. <!-- 一个Advisor里面对应一个advice~~~ -->
  12. <property name="advice">
  13. <bean class="com.fsx.aop.MyMethodInteceptor"/>
  14. </property>
  15. </bean>
  16. </beans>

把该xml配置文件导入Config配置类,让它生效

  1. @Configuration
  2. @ImportResource(locations = "classpath:spring.xml")
  3. public class RootConfig { ... }

启动Spring容器(采用JUnit测试):

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = {RootConfig.class})
  3. public class TestSpringBean {
  4. @Autowired
  5. private Person p;
  6. @Test
  7. public void test1() {
  8. System.out.println(p.getClass()); //class com.fsx.bean.Person$$EnhancerBySpringCGLIB$$cba1d735
  9. p.run();
  10. p.run(10);
  11. p.say();
  12. p.sayHi("Jack");
  13. p.say("Tom", 666);
  14. }
  15. }
  16. 输出:
  17. class com.fsx.bean.Person$$EnhancerBySpringCGLIB$$cba1d735 // 说明它是CGLIB的代理
  18. ============>放行前拦截...
  19. 我在run...
  20. ============>放行后拦截...
  21. 我在run...<10>
  22. 我在say...
  23. Hi,Jack,你好
  24. Tom----666

备注:此xml的配置方式其实是最原始的Spring AOP的使用。并没有使用到<aop:config>、<aop:pointcut>这种标签注解,关于使用它们的xml配置方式,此处不做过多介绍了~~~因为也比较简单~

AspectJExpressionPointcut源码分析

  1. // 很容易发现,自己即是ClassFilter,也是MethodMatcher
  2. // 它是子接口:ExpressionPointcut的实现类
  3. public class AspectJExpressionPointcut extends AbstractExpressionPointcut
  4. implements ClassFilter, IntroductionAwareMethodMatcher, BeanFactoryAware {
  5. ...
  6. private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = new HashSet<>();
  7. // 从此处可以看出,Spring支持的AspectJ的切点语言表达式一共有10中(加上后面的自己的Bean方式一共11种)
  8. // AspectJ框架本省支持的非常非常多,详解枚举类:org.aspectj.weaver.tools.PointcutPrimitive
  9. static {
  10. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION);
  11. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.ARGS);
  12. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.REFERENCE);
  13. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.THIS);
  14. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.TARGET);
  15. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.WITHIN);
  16. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ANNOTATION);
  17. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_WITHIN);
  18. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ARGS);
  19. SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_TARGET);
  20. }
  21. ...
  22. // 它持有BeanFactory 的引用,但是是可以为null的,也就是说它脱离容器也能够正常work
  23. @Nullable
  24. private BeanFactory beanFactory;
  25. ...
  26. // PointcutExpression是org.aspectj.weaver.tools.PointcutExpression是AspectJ的类
  27. // 它最终通过一系列操作,由org.aspectj.weaver.tools.PointcutParser#parsePointcutExpression从字符串表达式解析出来
  28. @Nullable
  29. private transient PointcutExpression pointcutExpression;
  30. ...
  31. // 由此可见,我们不仅仅可议写&& || !这种。也支持 and or not这种哦~~~
  32. private String replaceBooleanOperators(String pcExpr) {
  33. String result = StringUtils.replace(pcExpr, " and ", " && ");
  34. result = StringUtils.replace(result, " or ", " || ");
  35. result = StringUtils.replace(result, " not ", " ! ");
  36. return result;
  37. }
  38. ...
  39. // 这是ClassFilter 匹配类。借助的PointcutExpression#couldMatchJoinPointsInType 去匹配
  40. public boolean matches(Class<?> targetClass) { ... }
  41. // MethodMatcher 匹配方法,借助的PointcutExpression和ShadowMatch去匹配的
  42. public boolean matches(Method method, @Nullable Class<?> targetClass, boolean hasIntroductions) { ... }
  43. @Override
  44. public boolean isRuntime() {
  45. //mayNeedDynamicTest 相当于由AspectJ框架去判断的(是否有动态内容)
  46. return obtainPointcutExpression().mayNeedDynamicTest();
  47. }
  48. ...
  49. // 初始化一个Pointcut的解析器。我们发现最后一行,新注册了一个BeanPointcutDesignatorHandler 它是准们处理Spring自己支持的bean() 的切点表达式的
  50. private PointcutParser initializePointcutParser(@Nullable ClassLoader classLoader) {
  51. PointcutParser parser = PointcutParser
  52. .getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution(
  53. SUPPORTED_PRIMITIVES, classLoader);
  54. parser.registerPointcutDesignatorHandler(new BeanPointcutDesignatorHandler());
  55. return parser;
  56. }
  57. // 真正的解析,依赖于Spring自己实现的这个内部类(主要是ContextBasedMatcher 这个类,就会使用到BeanFactory了)
  58. private class BeanPointcutDesignatorHandler implements PointcutDesignatorHandler {
  59. private static final String BEAN_DESIGNATOR_NAME = "bean";
  60. @Override
  61. public String getDesignatorName() {
  62. return BEAN_DESIGNATOR_NAME;
  63. }
  64. // ContextBasedMatcher由Spring自己实现,对容器内Bean的匹配
  65. @Override
  66. public ContextBasedMatcher parse(String expression) {
  67. return new BeanContextMatcher(expression);
  68. }
  69. }
  70. }

NameMatchMethodPointcut

如果创建切入点时候,我们往往只需要方法名字匹配,无需理会方法的签名和返回类型,这种情况下,我们可以使用 NameMatchMethodPointCut方法名字匹配切入点。(这种功能最弱,但显然效率是最高的)

  1. public class Main {
  2. public static void main(String[] args) {
  3. ProxyFactory factory = new ProxyFactory(new Person());
  4. // 声明一个通知(此处使用环绕通知 MethodInterceptor )
  5. Advice advice = (MethodInterceptor) invocation -> {
  6. System.out.println("============>放行前拦截...");
  7. Object obj = invocation.proceed();
  8. System.out.println("============>放行后拦截...");
  9. return obj;
  10. };
  11. 声明一个aspectj切点,一张切面
  12. //NameMatchMethodPointcut cut = new NameMatchMethodPointcut();
  13. //cut.setMappedName("run"); //会匹配所有的方法名为run的方法
  14. 切点+通知
  15. //Advisor advisor = new DefaultPointcutAdvisor(cut, advice);
  16. NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
  17. advisor.setMappedName("run");
  18. advisor.setAdvice(advice);
  19. factory.addAdvisor(advisor);
  20. Person p = (Person) factory.getProxy();
  21. // 执行方法
  22. p.run();
  23. p.run(10);
  24. p.say();
  25. p.sayHi("Jack");
  26. p.say("Tom", 666);
  27. }
  28. }
  29. 输出:
  30. ============>放行前拦截...
  31. 我在run...
  32. ============>放行后拦截...
  33. ============>放行前拦截...
  34. 我在run...<10>
  35. ============>放行后拦截...
  36. 我在say...
  37. Hi,Jack,你好
  38. Tom----666

其它Pointcut

上面已经介绍了Spring中使用得比较多的Pointcut,接下来简单的讲述一下稍微偏门些的Pointcut。

从顶部的pointcut的继承图中可以看出,有很多实现类。

ControlFlowPointCut:流程切入点

如果有这样的特殊需求:我们对一个方法进行切入通知,但只有这个方法在一个特定方法中被调用的时候执行通知(即存在流程上行的依赖关系),我们可以使用ControlFlowPointCut流程切入点

  1. public class Main {
  2. public static void main(String[] args) {
  3. ProxyFactory factory = new ProxyFactory(new Person());
  4. // 声明一个通知(此处使用环绕通知 MethodInterceptor )
  5. Advice advice = (MethodInterceptor) invocation -> {
  6. System.out.println("============>放行前拦截...");
  7. Object obj = invocation.proceed();
  8. System.out.println("============>放行后拦截...");
  9. return obj;
  10. };
  11. 声明一个aspectj切点,一张切面
  12. // 含义:Main类里面,方法名为funabc执行时,内部调用的任何代理的方法都会被拦截~~~ 它控制的是整个流程
  13. ControlFlowPointcut cut = new ControlFlowPointcut(Main.class, "funabc");
  14. // 切点+通知
  15. Advisor advisor = new DefaultPointcutAdvisor(cut, advice);
  16. factory.addAdvisor(advisor);
  17. Person p = (Person) factory.getProxy();
  18. // 执行方法
  19. p.run();
  20. p.run(10);
  21. p.say();
  22. p.sayHi("Jack");
  23. p.say("Tom", 666);
  24. // 此处调用Main类,方法名为funabc的方法。内部代理对象的方法就都会被拦截上了
  25. funabc(p);
  26. }
  27. private static void funabc(Person person) {
  28. person.run();
  29. person.say();
  30. }
  31. }
  32. 输出:
  33. 我在run...
  34. 我在run...<10>
  35. 我在say...
  36. Hi,Jack,你好
  37. Tom----666
  38. ============>放行前拦截...
  39. 我在run...
  40. ============>放行后拦截...
  41. ============>放行前拦截...
  42. 我在say...
  43. ============>放行后拦截...

使用流程切入点有时候可以解决不少问题,但值得注意的是:

使用流程切入点在jdk1.4中比其他切入点要慢5倍,在1.3上则要慢10倍,追求高性能的要慎重使用

ComposablePointcut 组合切入点

从上面的例子中,每次我们只能定义一个切入点(切点表达式)。有的时候,一个切点可能难以描述目标连接点的信息,而是需要同时满足两个切入点才行,那么ComposablePointcut就派上了用场(aspectJ里面的&& ||等其实也能达到类似的效果)。

但是更好的方式是使用Spring提供的ComposalbePointcut把两个切点组合起来,通过切点的复合运行算表示,ComposalbePointcut可以将多个切点以并集或者交集的方式组合起来,提供切点之间复合运算的功能。

先看一个Demo:

  1. public class Main {
  2. public static void main(String[] args) {
  3. ProxyFactory factory = new ProxyFactory(new Person());
  4. // 声明一个通知(此处使用环绕通知 MethodInterceptor )
  5. Advice advice = (MethodInterceptor) invocation -> {
  6. System.out.println("============>放行前拦截...");
  7. Object obj = invocation.proceed();
  8. System.out.println("============>放行后拦截...");
  9. return obj;
  10. };
  11. // 先创建一个流程切入点
  12. ControlFlowPointcut controlFlowPointcut = new ControlFlowPointcut(Main.class, "funabc");
  13. // 再创建一个方法名切入点
  14. NameMatchMethodPointcut nameMatchMethodPointcut = new NameMatchMethodPointcut();
  15. nameMatchMethodPointcut.addMethodName("say");
  16. // 创建一个复合切点 把上面两者并且进来
  17. ComposablePointcut cut = new ComposablePointcut();
  18. cut.intersection((Pointcut) controlFlowPointcut).intersection((Pointcut)nameMatchMethodPointcut);
  19. // 切点+通知(注意:此处放的是复合切面)
  20. Advisor advisor = new DefaultPointcutAdvisor(cut, advice);
  21. factory.addAdvisor(advisor);
  22. Person p = (Person) factory.getProxy();
  23. // 执行方法
  24. p.run();
  25. p.run(10);
  26. p.say();
  27. p.sayHi("Jack");
  28. p.say("Tom", 666);
  29. funabc(p);
  30. }
  31. private static void funabc(Person person) {
  32. person.run();
  33. person.say();
  34. }
  35. }
  36. 输出:
  37. 我在run...
  38. 我在run...<10>
  39. 我在say...
  40. Hi,Jack,你好
  41. Tom----666
  42. 我在run...
  43. ============>放行前拦截...
  44. 我在say...
  45. ============>放行后拦截...

从结果中和上面对比我们能看出,两个切入点有并且的效果。(只有say方法被拦截了,run方法并没有被拦截)

ComposablePointcut 源码分析

  1. public class ComposablePointcut implements Pointcut, Serializable {
  2. // 它持有ClassFilter 和 MethodMatcher ,最终通过它去组合匹配
  3. private ClassFilter classFilter;
  4. private MethodMatcher methodMatcher;
  5. // 构造函数一个共5个
  6. // 匹配所有类所有方法的复合切点
  7. public ComposablePointcut() {
  8. this.classFilter = ClassFilter.TRUE;
  9. this.methodMatcher = MethodMatcher.TRUE;
  10. }
  11. // 匹配特定切点的复合切点(相当于把这个节点包装了一下而已)
  12. public ComposablePointcut(Pointcut pointcut) {
  13. Assert.notNull(pointcut, "Pointcut must not be null");
  14. this.classFilter = pointcut.getClassFilter();
  15. this.methodMatcher = pointcut.getMethodMatcher();
  16. }
  17. // 匹配特定类**所有方法**的复合切点
  18. public ComposablePointcut(ClassFilter classFilter) {
  19. Assert.notNull(classFilter, "ClassFilter must not be null");
  20. this.classFilter = classFilter;
  21. this.methodMatcher = MethodMatcher.TRUE;
  22. }
  23. // 匹配**所有类**特定方法的复合切点
  24. public ComposablePointcut(MethodMatcher methodMatcher) {
  25. Assert.notNull(methodMatcher, "MethodMatcher must not be null");
  26. this.classFilter = ClassFilter.TRUE;
  27. this.methodMatcher = methodMatcher;
  28. }
  29. // 匹配特定类特定方法的复合切点(这个是最为强大的)
  30. public ComposablePointcut(ClassFilter classFilter, MethodMatcher methodMatcher) {
  31. Assert.notNull(classFilter, "ClassFilter must not be null");
  32. Assert.notNull(methodMatcher, "MethodMatcher must not be null");
  33. this.classFilter = classFilter;
  34. this.methodMatcher = methodMatcher;
  35. }
  36. // 匹配特定类特定方法的复合切点(这个是最为强大的)
  37. public ComposablePointcut union(ClassFilter other) {
  38. this.classFilter = ClassFilters.union(this.classFilter, other);
  39. return this;
  40. }
  41. // ==========3个并集(union) / 3个交集(intersection) 运算的方法========
  42. public ComposablePointcut intersection(ClassFilter other) {
  43. this.classFilter = ClassFilters.intersection(this.classFilter, other);
  44. return this;
  45. }
  46. public ComposablePointcut union(MethodMatcher other) {
  47. this.methodMatcher = MethodMatchers.union(this.methodMatcher, other);
  48. return this;
  49. }
  50. public ComposablePointcut intersection(MethodMatcher other) {
  51. this.methodMatcher = MethodMatchers.intersection(this.methodMatcher, other);
  52. return this;
  53. }
  54. public ComposablePointcut union(Pointcut other) {
  55. this.methodMatcher = MethodMatchers.union(
  56. this.methodMatcher, this.classFilter, other.getMethodMatcher(), other.getClassFilter());
  57. this.classFilter = ClassFilters.union(this.classFilter, other.getClassFilter());
  58. return this;
  59. }
  60. public ComposablePointcut intersection(Pointcut other) {
  61. this.classFilter = ClassFilters.intersection(this.classFilter, other.getClassFilter());
  62. this.methodMatcher = MethodMatchers.intersection(this.methodMatcher, other.getMethodMatcher());
  63. return this;
  64. }
  65. ...
  66. }

ComposablePointcut没有提供直接对两个切点类型并集交集的运算的方法。若需要,请参照org.springframework.aop.support.Pointcuts这个工具类里面有对两个Pointcut进行并集、交集的操作(后面再介绍)

AnnotationMatchingPointcut 注解切入点

根据对象是否有指定类型的注解来匹配Pointcut

有两种注解,类级别注解和方法级别注解

  1. //仅指定类级别的注解, 标注了 ClassLevelAnnotation 注解的类中的**所有方法**执行的时候,将全部匹配。
  2. AnnotationMatchingPointcut pointcut = new AnnotationMatchingPointcut(ClassLevelAnnotation.class);
  3. // === 还可以使用静态方法创建 pointcut 实例
  4. AnnotationMatchingPointcut pointcut = AnnotationMatchingPointcut.forClassAnnotation(ClassLevelAnnotation.class);
  5. //仅指定方法级别的注解,标注了 MethodLeavelAnnotaion 注解的**方法(忽略类匹配)都将匹配**
  6. AnnotationMatchingPointcut pointcut = AnnotationMatchingPointcut.forMethodAnnotation(MethodLevelAnnotation.class);
  7. ==========这个是同时想限定:===============
  8. //同时限定类级别和方法级别的注解,只有标注了 ClassLevelAnnotation 的类中 ***同时***标注了 MethodLevelAnnotation 的方法才会匹配
  9. AnnotationMatchingPointcut pointcut = new AnnotationMatchingPointcut(ClassLevelAnnotation.class, MethodLevelAnnotation.class);

Demo:略

总结

其实,这些基础的知识也是为了去更好的理解Spring的自动代理创建器铺路

 

Advisor介绍

Advisor是Spring AOP的顶层抽象,用来管理AdvicePointcutPointcutAdvisor和切点有关,但IntroductionAdvisor和切点无关

注意:Advice是aopalliance对通知(增强器)的顶层抽象,请注意区分~~

Pointcut是Spring AOP对切点的抽象。切点的实现方式有多种,其中一种就是AspectJ

  1. public interface Advisor {
  2. //@since 5.0 Spring5以后才有的 空通知 一般当作默认值
  3. Advice EMPTY_ADVICE = new Advice() {};
  4. // 该Advisor 持有的通知器
  5. Advice getAdvice();
  6. // 这个有点意思:Spring所有的实现类都是return true(官方说暂时还没有应用到)
  7. // 注意:生成的Advisor是单例还是多例不由isPerInstance()的返回结果决定,而由自己在定义bean的时候控制
  8. // 理解:和类共享(per-class)或基于实例(per-instance)相关 类共享:类比静态变量 实例共享:类比实例变量
  9. boolean isPerInstance();
  10. }

它的继承体系主要有如下两个:PointcutAdvisorIntroductionAdvisor

0

IntroductionAdvisor与PointcutAdvisor最本质上的区别就是,IntroductionAdvisor只能应用于类级别的拦截,只能使用Introduction型的Advice。

而不能像PointcutAdvisor那样,可以使用任何类型的Pointcut,以及几乎任何类型的Advice

PointcutAdvisor:和切点有关的Advisor

顾名思义,它和Pointcu有关。

其实我们已经介绍了好几个PointcutAdvisor。比如:RegexpMethodPointcutAdvisorNameMatchMethodPointcutAdvisor,它哥俩都位于org.springframework.aop.support此包。当然还要介绍过AspectJExpressionPointcutAdvisor

PointcutAdvisor它的实现类非常的多:

  1. public interface PointcutAdvisor extends Advisor {
  2. Pointcut getPointcut();
  3. }

https://note.youdao.com/yws/public/resource/c9bde74fde820328f08b053548d5d3e8/xmlnote/9D1C072DE2F1440EBAEDD6A2A2E1892D/7414

AbstractPointcutAdvisor:抽象实现

  1. // 实现了 Ordered接口
  2. public abstract class AbstractPointcutAdvisor implements PointcutAdvisor, Ordered, Serializable {
  3. // 调用者可以手动来指定Order
  4. public void setOrder(int order) {
  5. this.order = order;
  6. }
  7. @Override
  8. public int getOrder() {
  9. if (this.order != null) {
  10. return this.order;
  11. }
  12. // 若调用者没有指定Order,那就拿advice的order为准(若有),否则LOWEST_PRECEDENCE表示最后执行
  13. Advice advice = getAdvice();
  14. if (advice instanceof Ordered) {
  15. return ((Ordered) advice).getOrder();
  16. }
  17. return Ordered.LOWEST_PRECEDENCE;
  18. }
  19. // Spring还没有使用该属性 永远返回true了
  20. @Override
  21. public boolean isPerInstance() {
  22. return true;
  23. }
  24. ...
  25. }

AbstractGenericPointcutAdvisor 一般的、通用的PointcutAdvisor

  1. public abstract class AbstractGenericPointcutAdvisor extends AbstractPointcutAdvisor {
  2. private Advice advice = EMPTY_ADVICE;
  3. public void setAdvice(Advice advice) {
  4. this.advice = advice;
  5. }
  6. @Override
  7. public Advice getAdvice() {
  8. return this.advice;
  9. }
  10. ...
  11. }

DefaultPointcutAdvisor 通用的,最强大的Advisor

它是Spring提供的通用的,也被认为是最强大的Advisor。它可以把任意的两个Advice和Pointcut放在一起:

  1. public class DefaultPointcutAdvisor extends AbstractGenericPointcutAdvisor implements Serializable {
  2. private Pointcut pointcut = Pointcut.TRUE;
  3. public DefaultPointcutAdvisor() {
  4. }
  5. // 若没有指定advice,默认Pointcut.TRUE,也就是说会匹配所有的方法的执行
  6. public DefaultPointcutAdvisor(Advice advice) {
  7. this(Pointcut.TRUE, advice);
  8. }
  9. // 显然,这个构造函数式非常强大的~~
  10. public DefaultPointcutAdvisor(Pointcut pointcut, Advice advice) {
  11. this.pointcut = pointcut;
  12. setAdvice(advice);
  13. }
  14. }

AbstractBeanFactoryPointcutAdvisor:和bean工厂有关的PointcutAdvisor

从命名也能看出来,它和BeanFactory有关。

  1. // 实现了BeanFactoryAware接口,若在Bean容器里注册可议注入BeanFactory~~~从而访问里面的实例
  2. public abstract class AbstractBeanFactoryPointcutAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {
  3. // 我们发现这两个都是@Nullable,所以他们脱离容器使用也是可以的
  4. @Nullable
  5. private String adviceBeanName;
  6. @Nullable
  7. private BeanFactory beanFactory;
  8. @Nullable
  9. private transient volatile Advice advice;
  10. public void setAdviceBeanName(@Nullable String adviceBeanName) {
  11. this.adviceBeanName = adviceBeanName;
  12. }
  13. @Override
  14. public void setBeanFactory(BeanFactory beanFactory) {
  15. this.beanFactory = beanFactory;
  16. // 若在Spring环境下,会给AdviceMonitor重新赋值为:getSingletonMutex()
  17. resetAdviceMonitor();
  18. }
  19. // 此处加锁
  20. public void setAdvice(Advice advice) {
  21. synchronized (this.adviceMonitor) {
  22. this.advice = advice;
  23. }
  24. }
  25. // 这是它最重要的方法,获取增强器
  26. @Override
  27. public Advice getAdvice() {
  28. Advice advice = this.advice;
  29. // 非Spring环境一般手动set进来,所以就直接返回吧
  30. if (advice != null) {
  31. return advice;
  32. }
  33. // 显然进来Spring容器环境了,bean工厂和beanName都是不能为null的
  34. Assert.state(this.adviceBeanName != null, "'adviceBeanName' must be specified");
  35. Assert.state(this.beanFactory != null, "BeanFactory must be set to resolve 'adviceBeanName'");
  36. // 若bean是单例的 那就没什么好说的 直接去工厂里拿出来就完事了(Advice.class) 有可能返回null哦
  37. if (this.beanFactory.isSingleton(this.adviceBeanName)) {
  38. advice = this.beanFactory.getBean(this.adviceBeanName, Advice.class);
  39. this.advice = advice;
  40. return advice;
  41. }
  42. // 若是多例的,就加锁 然后调用getBean()给他生成一个新的实例即可
  43. else {
  44. synchronized (this.adviceMonitor) {
  45. //这步赋值和判断不能省~~~确保万无一失
  46. advice = this.advice;
  47. if (advice == null) {
  48. advice = this.beanFactory.getBean(this.adviceBeanName, Advice.class);
  49. this.advice = advice;
  50. }
  51. return advice;
  52. }
  53. }
  54. }
  55. }

DefaultBeanFactoryPointcutAdvisor:通用的BeanFactory的Advisor

这个是和Bean工厂关联的,通用的PointcutAdvisor

  1. public class DefaultBeanFactoryPointcutAdvisor extends AbstractBeanFactoryPointcutAdvisor {
  2. private Pointcut pointcut = Pointcut.TRUE;
  3. // 若传进来为null,还是选择 Pointcut.TRUE 匹配所有
  4. public void setPointcut(@Nullable Pointcut pointcut) {
  5. this.pointcut = (pointcut != null ? pointcut : Pointcut.TRUE);
  6. }
  7. @Override
  8. public Pointcut getPointcut() {
  9. return this.pointcut;
  10. }
  11. }

在Spring事务相关里,你会看到这个类

位于org.springframework.aop.support包内

BeanFactoryCacheOperationSourceAdvisor:和Cache有关

Spring Cache的@Cachable等注解的拦截,就是采用了它。该类位于:org.springframework.cache.interceptor,显然它和cache相关了。Jar包属于:Spring-context.jar

  1. // @since 3.1 毕竟Spring的整个org.springframework.cache.Cache体系都是从这里开始的。(@Cacheable...等等)
  2. public class BeanFactoryCacheOperationSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
  3. // 显然它最重要的是持有这个引用(Cache章节详细介绍了它)
  4. @Nullable
  5. private CacheOperationSource cacheOperationSource;
  6. // Pointcut使用的是CacheOperationSourcePointcut
  7. private final CacheOperationSourcePointcut pointcut = new CacheOperationSourcePointcut() {
  8. @Override
  9. @Nullable
  10. protected CacheOperationSource getCacheOperationSource() {
  11. return cacheOperationSource;
  12. }
  13. };
  14. public void setCacheOperationSource(CacheOperationSource cacheOperationSource) {
  15. this.cacheOperationSource = cacheOperationSource;
  16. }
  17. public void setClassFilter(ClassFilter classFilter) {
  18. this.pointcut.setClassFilter(classFilter);
  19. }
  20. @Override
  21. public Pointcut getPointcut() {
  22. return this.pointcut;
  23. }
  24. }

AsyncAnnotationAdvisor:和@Async有关

位于包为:org.springframework.scheduling.annotation,所属jar包为spring-context.jar

  1. public class AsyncAnnotationAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {
  2. // 处理异步发生的异常的====
  3. private AsyncUncaughtExceptionHandler exceptionHandler;
  4. private Advice advice;
  5. private Pointcut pointcut;
  6. // 构造函数们
  7. public AsyncAnnotationAdvisor() {
  8. this(null, null);
  9. }
  10. // executor:可以自己指定异步任务的执行器
  11. // exceptionHandler:异步异常的处理器
  12. public AsyncAnnotationAdvisor(@Nullable Executor executor, @Nullable AsyncUncaughtExceptionHandler exceptionHandler) {
  13. Set<Class<? extends Annotation>> asyncAnnotationTypes = new LinkedHashSet<>(2);
  14. asyncAnnotationTypes.add(Async.class);
  15. // 支持EJB的注解:@Asynchronous
  16. try {
  17. asyncAnnotationTypes.add((Class<? extends Annotation>)
  18. ClassUtils.forName("javax.ejb.Asynchronous", AsyncAnnotationAdvisor.class.getClassLoader()));
  19. } catch (ClassNotFoundException ex) {
  20. // If EJB 3.1 API not present, simply ignore.
  21. }
  22. if (exceptionHandler != null) {
  23. this.exceptionHandler = exceptionHandler;
  24. } else {
  25. // SimpleAsyncUncaughtExceptionHandler:只是一个简单的logger.error的输入打印
  26. this.exceptionHandler = new SimpleAsyncUncaughtExceptionHandler();
  27. }
  28. // buildAdvice: new AnnotationAsyncExecutionInterceptor(executor, exceptionHandler) 它是个MethodInterceptor 环绕通知器
  29. this.advice = buildAdvice(executor, this.exceptionHandler);
  30. // 把asyncAnnotationTypes交给buildPointcut,它最终是个ComposablePointcut,会把这两种注解都支持。union起来 或者的关系
  31. this.pointcut = buildPointcut(asyncAnnotationTypes);
  32. }
  33. public void setTaskExecutor(Executor executor) {
  34. this.advice = buildAdvice(executor, this.exceptionHandler);
  35. }
  36. ...
  37. }

AbstractAspectJAdvice的实现类如下:这5个实现类完完整整的对应着我们AspectJ的那5个注解。

0


AspectJPointcutAdvisor

显然是和AspectJ相关的,使用得很是广泛。注意它和AspectJExpressionPointcutAdvisor的区别。有名字也能看出来,AspectJExpressionPointcutAdvisor和表达式语言的切点相关的,而AspectJPointcutAdvisor是无关的。它哥俩都位于包org.springframework.aop.aspectj里。

  1. public class AspectJPointcutAdvisor implements PointcutAdvisor, Ordered {
  2. // AbstractAspectJAdvice通知:它的子类看下面截图,就非常清楚了
  3. private final AbstractAspectJAdvice advice;
  4. // 可以接受任意的Pointcut,可谓非常的通用(当然也包含切点表达式啦)
  5. private final Pointcut pointcut;
  6. @Nullable
  7. private Integer order;
  8. // 只有这一个构造函数,包装一个advice
  9. public AspectJPointcutAdvisor(AbstractAspectJAdvice advice) {
  10. Assert.notNull(advice, "Advice must not be null");
  11. this.advice = advice;
  12. // 然后pointcut根据advice直接给生成了一个。这是AbstractAspectJAdvice#buildSafePointcut的方法
  13. this.pointcut = advice.buildSafePointcut();
  14. }
  15. }

InstantiationModelAwarePointcutAdvisor

它是PointcutAdvisor的一个子接口。

  1. // 由SpringAOP顾问包装AspectJ实现的接口 可能具有延迟初始化策略的方面。
  2. // 例如,一个PerThis实例化模型意味着对建议的初始化太慢
  3. public interface InstantiationModelAwarePointcutAdvisor extends PointcutAdvisor {
  4. // 该Advisor是否需要懒加载
  5. boolean isLazy();
  6. // 判断此Advisor它所拥有的Advice是否已经初始化了
  7. boolean isAdviceInstantiated();
  8. }

它的唯一实现类:InstantiationModelAwarePointcutAdvisorImpl

  1. // 默认的访问权限,显然是Spring内部自己用的
  2. class InstantiationModelAwarePointcutAdvisorImpl
  3. implements InstantiationModelAwarePointcutAdvisor, AspectJPrecedenceInformation, Serializable {
  4. private static final Advice EMPTY_ADVICE = new Advice() {};
  5. // 和AspectJExpression
  6. private final AspectJExpressionPointcut declaredPointcut;
  7. ..
  8. // 通知方法
  9. private transient Method aspectJAdviceMethod;
  10. private final AspectJAdvisorFactory aspectJAdvisorFactory;
  11. private final MetadataAwareAspectInstanceFactory aspectInstanceFactory;
  12. @Nullable
  13. private Advice instantiatedAdvice;
  14. @Nullable
  15. private Boolean isBeforeAdvice;
  16. @Nullable
  17. private Boolean isAfterAdvice;
  18. ...
  19. @Override
  20. public boolean isPerInstance() {
  21. return (getAspectMetadata().getAjType().getPerClause().getKind() != PerClauseKind.SINGLETON);
  22. }
  23. @Override
  24. public synchronized Advice getAdvice() {
  25. if (this.instantiatedAdvice == null) {
  26. this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut);
  27. }
  28. return this.instantiatedAdvice;
  29. }
  30. // advice 由aspectJAdvisorFactory去生产 懒加载的效果
  31. private Advice instantiateAdvice(AspectJExpressionPointcut pointcut) {
  32. Advice advice = this.aspectJAdvisorFactory.getAdvice(this.aspectJAdviceMethod, pointcut,
  33. this.aspectInstanceFactory, this.declarationOrder, this.aspectName);
  34. return (advice != null ? advice : EMPTY_ADVICE);
  35. }
  36. @Override
  37. public boolean isBeforeAdvice() {
  38. if (this.isBeforeAdvice == null) {
  39. determineAdviceType();
  40. }
  41. return this.isBeforeAdvice;
  42. }
  43. @Override
  44. public boolean isAfterAdvice() {
  45. if (this.isAfterAdvice == null) {
  46. determineAdviceType();
  47. }
  48. return this.isAfterAdvice;
  49. }
  50. // 这里解释根据@Aspect方法上标注的注解,来区分这两个字段的值的
  51. private void determineAdviceType() {
  52. AspectJAnnotation<?> aspectJAnnotation =
  53. AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(this.aspectJAdviceMethod);
  54. if (aspectJAnnotation == null) {
  55. this.isBeforeAdvice = false;
  56. this.isAfterAdvice = false;
  57. }
  58. else {
  59. switch (aspectJAnnotation.getAnnotationType()) {
  60. case AtAfter:
  61. case AtAfterReturning:
  62. case AtAfterThrowing:
  63. this.isAfterAdvice = true;
  64. this.isBeforeAdvice = false;
  65. break;
  66. case AtAround:
  67. case AtPointcut:
  68. this.isAfterAdvice = false;
  69. this.isBeforeAdvice = false;
  70. break;
  71. case AtBefore:
  72. this.isAfterAdvice = false;
  73. this.isBeforeAdvice = true;
  74. }
  75. }
  76. }
  77. }

这个Advisor是在Spring解析被 @AspectJ注解注释的类时生成的 Advisor,。

而这个 Advisor中的 PointcutAdvice都是由ReflectiveAspectJAdvisorFactory 来解析生成的(与之对应的 Advice 是 AspectJMethodBeforeAdvice, AspectJAfterAdvice, AspectJAfterReturningAdvice, AspectJAfterThrowingAdvice, AspectJAroundAdvice,

Pointcut 则是AspectJExpressionPointcut), 解析的步骤是:

自动代理创建器:AnnotationAwareAspectJAutoProxyCreator.findCandidateAdvisors() ->

Bean工厂相关的Advisor构建器:BeanFactoryAspectJAdvisorsBuilder.buildAspectJAdvisors() ->

ReflectiveAspectJAdvisorFactory.getAdvisors() ->

ReflectiveAspectJAdvisorFactory.getAdvisor() 最终生成了InstantiationModelAwarePointcutAdvisorImpl(当然包括里面的 Pointcut与 advice 也都是由 ReflectiveAspectJAdvisorFactory 解析生成的)


IntroductionAdvisor:引介切面

Spring中有五种增强:BeforeAdvide(前置增强)、AfterAdvice(后置增强)、ThrowsAdvice(异常增强)、RoundAdvice(环绕增强)、IntroductionAdvice(引入增强)

RoundAdvice(环绕增强):就是BeforeAdvide(前置增强)、AfterAdvice(后置增强)的组合使用叫环绕增强。前四种都比较简单。。。

引入增强(Introduction Advice)的概念:一个Java类,没有实现A接口,在不修改Java类的情况下,使其具备A接口的功能。(非常强大有木有,A不需要动代码,就能有别的功能,吊炸天有木有)

IntroductionAdvisor纯粹就是为Introduction而生的。

IntroductionAdvisor 和 PointcutAdvisor接口不同,它仅有一个类过滤器ClassFilter 而没有 MethodMatcher,这是因为 `引介切面 的切点是类级别的,而 Pointcut 的切点是方法级别的(细粒度更细,所以更加常用)。

为了更好的了解IntroductionAdvisor,我先有必要讲解下IntroductionInfoIntroductionInterceptor

Introduction可以在不改动目标类定义的情况下,为目标类增加新的属性和行为。

IntroductionInfo:引介信息

IntroductionInfo 接口描述了目标类需要实现的新接口。

  1. // 提供描述引言所需信息的接口
  2. // IntroductionAdvisor必须实现这个接口。若`org.aopalliance.aop.Advice`直接实现了此接口,
  3. // 它可议独立的当作introduction来使用而不用依赖IntroductionAdvisor。这种情况下,这个advice可议自描述,不仅提供。。。
  4. public interface IntroductionInfo {
  5. //Return the additional interfaces introduced by this Advisor or Advice.
  6. // 返回额外给Advisor 或者 advice实现的接口们
  7. Class<?>[] getInterfaces();
  8. }

它的继承结构如下:

0

IntroductionInterceptor:引介拦截器

在Spring中,为目标对象添加新的属性和行为必须声明相应的接口以及相应的实现。这样,再通过特定的拦截器将新的接口定义以及实现类中的逻辑附加到目标对象上。然后,目标对象(确切的说,是目标对象的代理对象)就拥有了新的状态和行为

这里面介绍这个非常强大的拦截器:IntroductionInterceptor

  1. // IntroductionInterceptor它是对MethodInterceptor的一个扩展,同时他还继承了接口DynamicIntroductionAdvice
  2. public interface IntroductionInterceptor extends MethodInterceptor, DynamicIntroductionAdvice {
  3. }

DynamicIntroductionAdvice

  1. public interface DynamicIntroductionAdvice extends Advice {
  2. boolean implementsInterface(Class<?> intf);
  3. }

通过DynamicIntroductionAdvice,可以界定当前的 IntroductionInterceptor为哪些接口提供相应的拦截功能。通过MethodInterceptor,IntroductionInterceptor 就可以处理新添加的接口上的方法调用了

打个比方

如果把每个目标对象实例看作盒装牛奶生产线上的那一盒盒牛奶的话,那么生产合格证就是新的Introduction逻辑,而introductionInterceptor 就是把这些生产合格证贴到一盒盒牛奶上的那个人

要对目标对象进行拦截并添加Introduction的逻辑,我们可以直接扩展IntroductionInterceptor,然后在子类的invoke方法中实现所有的拦截逻辑

除非特殊情况下需要直接扩展IntroductionInterceptor,大多数时候,直接使用Spring提供的两个现成的实现类就可以了:DelegatingIntroductionInterceptor DelegatePerTargetObjectIntroductionInterceptor

0

例子

下面使用一个例子,加深一下对引介增强的了解:

  1. // 定义一个新的行为接口,这个行为准备作用在目标对象上
  2. public interface IOtherInte {
  3. void doOther();
  4. }
  5. // 自己定义一个IntroductionInterceptor来实现IntroductionInterceptor接口
  6. // 注意:此处也实现了接口IOtherInte(这是类似于增强器部分) 相当于这个interptor目前就只处理 IOtherInte
  7. public class SomeInteIntroductionInterceptor implements IntroductionInterceptor, IOtherInte {
  8. /**
  9. * 判断调用的方法是否为指定类中的方法
  10. * 如果Method代表了一个方法 那么调用它的invoke就相当于执行了它代表的这个方法
  11. */
  12. @Override
  13. public Object invoke(MethodInvocation invocation) throws Throwable {
  14. if (implementsInterface(invocation.getMethod().getDeclaringClass())) {
  15. System.out.println("我是引介增强的方法体~~~invoke");
  16. return invocation.getMethod().invoke(this, invocation.getArguments());
  17. }
  18. return invocation.proceed();
  19. }
  20. /**
  21. * 判断clazz是否为给定接口IOtherBean的实现
  22. */
  23. @Override
  24. public boolean implementsInterface(Class clazz) {
  25. return clazz.isAssignableFrom(IOtherInte.class);
  26. }
  27. @Override
  28. public void doOther() {
  29. System.out.println("给人贴标签 doOther...");
  30. }
  31. }
  32. // 方法测试
  33. public static void main(String[] args) {
  34. ProxyFactory factory = new ProxyFactory(new Person());
  35. factory.setProxyTargetClass(true); // 强制私用CGLIB 以保证我们的Person方法也能正常调用
  36. // 此处采用IntroductionInterceptor 这个引介增强的拦截器
  37. Advice advice = new SomeInteIntroductionInterceptor();
  38. // 切点+通知(注意:此处放的是复合切面)
  39. Advisor advisor = new DefaultIntroductionAdvisor((DynamicIntroductionAdvice) advice, IOtherInte.class);
  40. //Advisor advisor = new DefaultPointcutAdvisor(cut, advice);
  41. factory.addAdvisor(advisor);
  42. IOtherInte otherInte = (IOtherInte) factory.getProxy();
  43. otherInte.doOther();
  44. System.out.println("===============================");
  45. // Person本身自己的方法 也得到了保留
  46. Person p = (Person) factory.getProxy();
  47. p.run();
  48. p.say();
  49. }
  50. 输出:
  51. 我是引介增强的方法体~~~invoke
  52. 给人贴标签 doOther...
  53. ===============================
  54. 我在run...
  55. 我在say...

我们发现,我们没有更改过Person类的任何代码,它竟然就有了doOther()方法的功能,这就是引介增强的强大功能。此处使用的AdvisorDefaultIntroductionAdvisor。它也是我们最常用的Advisor:

  1. // 它是一个Advisor,同时也是一个IntroductionInfo
  2. public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
  3. // 它只有ClassFilter,因为它只能作用在类层面上
  4. ClassFilter getClassFilter();
  5. // 判断这些接口,是否真的能够增强。 DynamicIntroductionAdvice#implementsInterface()方法
  6. void validateInterfaces() throws IllegalArgumentException;
  7. }
  8. // 它直接事IntroductionAdvisor的实现类。同时也是一个ClassFilter
  9. public class DefaultIntroductionAdvisor implements IntroductionAdvisor, ClassFilter, Ordered, Serializable {
  10. private final Advice advice;
  11. private final Set<Class<?>> interfaces = new LinkedHashSet<>();
  12. private int order = Ordered.LOWEST_PRECEDENCE;
  13. // 构造函数们
  14. public DefaultIntroductionAdvisor(Advice advice) {
  15. this(advice, (advice instanceof IntroductionInfo ? (IntroductionInfo) advice : null));
  16. }
  17. // 如果IntroductionInfo 不等于null,就会把接口都add进去/
  18. // IntroductionInfo 的实现类有常用的:DelegatingIntroductionInterceptor和DelegatePerTargetObjectIntroductionInterceptor
  19. public DefaultIntroductionAdvisor(Advice advice, @Nullable IntroductionInfo introductionInfo) {
  20. Assert.notNull(advice, "Advice must not be null");
  21. this.advice = advice;
  22. if (introductionInfo != null) {
  23. Class<?>[] introducedInterfaces = introductionInfo.getInterfaces();
  24. if (introducedInterfaces.length == 0) {
  25. throw new IllegalArgumentException("IntroductionAdviceSupport implements no interfaces");
  26. }
  27. for (Class<?> ifc : introducedInterfaces) {
  28. addInterface(ifc);
  29. }
  30. }
  31. }
  32. //当然你也可以不使用IntroductionInfo,而自己手动指定了这个接口
  33. public DefaultIntroductionAdvisor(DynamicIntroductionAdvice advice, Class<?> intf) {
  34. Assert.notNull(advice, "Advice must not be null");
  35. this.advice = advice;
  36. addInterface(intf);
  37. }
  38. ...
  39. @Override
  40. public void validateInterfaces() throws IllegalArgumentException {
  41. for (Class<?> ifc : this.interfaces) {
  42. if (this.advice instanceof DynamicIntroductionAdvice &&
  43. !((DynamicIntroductionAdvice) this.advice).implementsInterface(ifc)) {
  44. throw new IllegalArgumentException("DynamicIntroductionAdvice [" + this.advice + "] " +
  45. "does not implement interface [" + ifc.getName() + "] specified for introduction");
  46. }
  47. }
  48. }
  49. ...
  50. }

 

DelegatingIntroductionInterceptor和DelegatePerTargetObjectIntroductionInterceptor

这两个类是 Spring AOP 中为 IntroductionInterceptor 介面所提供的实作类别,我们可以直接继承他俩,然后扩展我们自己的行为状态。

  1. public class DelegatingIntroductionInterceptor extends IntroductionInfoSupport
  2. implements IntroductionInterceptor {
  3. // 需要被代理的那个对象。因为这个类需要子类继承使用,所以一般都是thid
  4. @Nullable
  5. private Object delegate;
  6. /**
  7. * Construct a new DelegatingIntroductionInterceptor.
  8. * The delegate will be the subclass, which must implement
  9. * additional interfaces.
  10. * 访问权限事protected,显然就是说子类必须去继承这个类,然后提供空构造函数。代理类就是this
  11. */
  12. protected DelegatingIntroductionInterceptor() {
  13. init(this);
  14. }
  15. // 当然,你也可以手动指定delegate
  16. public DelegatingIntroductionInterceptor(Object delegate) {
  17. init(delegate);
  18. }
  19. private void init(Object delegate) {
  20. Assert.notNull(delegate, "Delegate must not be null");
  21. this.delegate = delegate;
  22. implementInterfacesOnObject(delegate);
  23. // 移除调这些内部标记的接口们
  24. // We don't want to expose the control interface
  25. suppressInterface(IntroductionInterceptor.class);
  26. suppressInterface(DynamicIntroductionAdvice.class);
  27. }
  28. // 如果你要自定义一些行为:比如环绕通知之类的,子类需要复写此方法(否则没有必要了)
  29. @Override
  30. @Nullable
  31. public Object invoke(MethodInvocation mi) throws Throwable {
  32. // 判断是否是引介增强
  33. if (isMethodOnIntroducedInterface(mi)) {
  34. Object retVal = AopUtils.invokeJoinpointUsingReflection(this.delegate, mi.getMethod(), mi.getArguments());
  35. // 如果返回值就是delegate 本身,那就把本身返回出去
  36. if (retVal == this.delegate && mi instanceof ProxyMethodInvocation) {
  37. Object proxy = ((ProxyMethodInvocation) mi).getProxy();
  38. if (mi.getMethod().getReturnType().isInstance(proxy)) {
  39. retVal = proxy;
  40. }
  41. }
  42. return retVal;
  43. }
  44. return doProceed(mi);
  45. }
  46. ...
  47. }

因此,上面的例子Demo,我用DelegatingIntroductionInterceptor改造一下(只需要改造SomeInteIntroductionInterceptor即可):

  1. // 因为我们继承自DelegatingIntroductionInterceptor,所以若我们不做环绕通知个性化,只需要实现接口的方法即可
  2. public class SomeInteIntroductionInterceptor extends DelegatingIntroductionInterceptor implements IOtherInte {
  3. @Override
  4. public void doOther() {
  5. System.out.println("给人贴标签 doOther...");
  6. }
  7. }

继承此类,确实少了不少事呢。

DelegatePerTargetObjectIntroductionInterceptor

DelegatingIntroductionInterceptor不同,DelegatePerTargetObjectIntroductionInterceptor会在内部持有一个目标对象与相应Introduction逻辑实现类之间的映射关系

当每个目标对象上的新定义的接口方法被调用的时候,它会拦截这些调用。然后以目标对象实例作为键,到它持有的那个映射关系中取得对应当前目标对象实例的Introduction实现类实例。 使用起来和DelegatingIntroductionInterceptor没有太大区别,主要在构造函数上:

  1. 1: 可以删除掉SomeInteIntroductionInterceptor类了
  2. 2:单独实现引介接口
  3. public class OtherImpl implements IOtherInte {
  4. @Override
  5. public void doOther() {
  6. System.out.println("我是OtherImpl");
  7. }
  8. }
  9. main方法里修改如下:这样就ok了
  10. Advice advice = new DelegatePerTargetObjectIntroductionInterceptor(OtherImpl.class, IOtherInte.class);

备注:若你需要复写invoke方法的逻辑,请扩展它即可~~~(它的优点是:每次执行目标对象的时候,都可议缓存起来,提高一点效率吧)

总结

Advisor是Spring AOP中非常重要的一个概念,最终代理对象进行执行什么的,都是适配到此处,因此需要重点掌握。

其中,引介增强平时使用得较少,但是在特殊的场景下,它能够解决某一类问题,还是非常不错的~

 

事务

DataSourceTransactionManager:

0

 

TransactionAttribute

这个接口是在TransactionDefinition的基础上的扩展

// 它继承自TransactionDefinition ,所有可以定义事务的基础属性 public interface TransactionAttribute extends TransactionDefinition { // 返回与此事务属性关联的限定符值 //@since 3.0 @Nullable String getQualifier(); // Should we roll back on the given exception? boolean rollbackOn(Throwable ex); }

0

它的主要实现类有:DefaultTransactionAttributeRuleBasedTransactionAttributeDelegatingTransactionAttribute

DefaultTransactionAttribute

默认的事务属性实现,也是最常用的一个实现。

  1. // 它继承自DefaultTransactionDefinition
  2. public class DefaultTransactionAttribute extends DefaultTransactionDefinition implements TransactionAttribute {
  3. @Nullable
  4. private String qualifier;
  5. @Nullable
  6. private String descriptor;
  7. // 你自己也可以自定义一个TransactionAttribute other 来替换掉一些默认行为
  8. public DefaultTransactionAttribute() {
  9. super();
  10. }
  11. public DefaultTransactionAttribute(TransactionAttribute other) {
  12. super(other);
  13. }
  14. // @since 3.0
  15. public void setQualifier(@Nullable String qualifier) {
  16. this.qualifier = qualifier;
  17. }
  18. @Override
  19. @Nullable
  20. public String getQualifier() {
  21. return this.qualifier;
  22. }
  23. ...
  24. // 可以清晰的看到:默认只回滚RuntimeException 或者 Error(比如OOM这种)
  25. @Override
  26. public boolean rollbackOn(Throwable ex) {
  27. return (ex instanceof RuntimeException || ex instanceof Error);
  28. }
  29. }

RuleBasedTransactionAttribute

这个在基础实现的基础上扩展了一下,扩展了一些规则。

  1. public class RuleBasedTransactionAttribute extends DefaultTransactionAttribute implements Serializable {
  2. /** Prefix for rollback-on-exception rules in description strings. */
  3. public static final String PREFIX_ROLLBACK_RULE = "-";
  4. /** Prefix for commit-on-exception rules in description strings. */
  5. public static final String PREFIX_COMMIT_RULE = "+";
  6. // RollbackRuleAttribute:它是个实体类,确定给定异常是否应导致回滚的规则
  7. // 相当于封装了这个规则的一个实体,内部封装一个异常 提供一个实例变量: 这个变量相当于回滚规则为只回滚RuntimeException
  8. // public static final RollbackRuleAttribute ROLLBACK_ON_RUNTIME_EXCEPTIONS = new RollbackRuleAttribute(RuntimeException.class);
  9. // 所以此类最重要的一个属性,就是这个,它能维护多种回滚的规则~~~~
  10. @Nullable
  11. private List<RollbackRuleAttribute> rollbackRules;
  12. ...
  13. public List<RollbackRuleAttribute> getRollbackRules() {
  14. if (this.rollbackRules == null) {
  15. this.rollbackRules = new LinkedList<>();
  16. }
  17. return this.rollbackRules;
  18. }
  19. // 核心逻辑输入,复写了父类的rollbackOn方法。也就是看看当前异常是否需要回滚呢???
  20. @Override
  21. public boolean rollbackOn(Throwable ex) {
  22. RollbackRuleAttribute winner = null;
  23. int deepest = Integer.MAX_VALUE;
  24. // 这里getDepth()就是去看看异常栈里面 该类型的异常处于啥位置。
  25. // 这里用了Integer的最大值,基本相当于不管异常有多深,遇上此异常都应该回滚喽,也就是找到这个winnner了~~~~~
  26. if (this.rollbackRules != null) {
  27. for (RollbackRuleAttribute rule : this.rollbackRules) {
  28. int depth = rule.getDepth(ex);
  29. if (depth >= 0 && depth < deepest) {
  30. deepest = depth;
  31. winner = rule;
  32. }
  33. }
  34. }
  35. // User superclass behavior (rollback on unchecked) if no rule matches.
  36. // 这句相当于:如果你没有指定回滚规则,那就交给父类吧(只回滚RuntimeException和Error类型)
  37. if (winner == null) {
  38. return super.rollbackOn(ex);
  39. }
  40. // 最终只要找到了,但是不是NoRollbackRuleAttribute类型就成`~~~~
  41. return !(winner instanceof NoRollbackRuleAttribute);
  42. }
  43. }

DelegatingTransactionAttribute

很显然,它就是一个简单的代理,内部持有一个TransactionAttribute的引用。自己也是个抽象类,没做啥事,此处略过。它也继承自:DelegatingTransactionDefinition

TransactionDefinition

事务的定义,上面已经介绍了一个重要分支:TransactionAttribute。接下来继续介绍另外一个分支:

DelegatingTransactionDefinition

一样的也就是个代理抽象类,啥都木有做。内部持有一个TransactionDefinition targetDefinition的引用而已,所有方法都是委托给targetDefinition去做的

ResourceTransactionDefinition

这个子接口非常的新,是Spring5.1才提供的

  1. // @since 5.1
  2. // 指示资源事务,尤其是事务性资源是否准备好进行本地优化
  3. public interface ResourceTransactionDefinition extends TransactionDefinition {
  4. // 确定事务性资源是否准备好进行本地优化
  5. // @see #isReadOnly()
  6. boolean isLocalResource();
  7. }

它和ResourceTransactionManager的使用相关联。ResourceTransactionManagerPlatformTransactionManager的一个子接口。

我们最常用的事务管理器DataSourceTransactionManager也实现了这个接口~~~~

目前Spring还未提供任何ResourceTransactionDefinition它的具体实现~

TransactionAttributeSource:事务属性源

它位于包:org.springframework.transaction.interceptor

它有点类似于之前讲过的TargetSource,它也是对TransactionAttribute进行了一层包装~~

  1. public interface TransactionAttributeSource {
  2. // 通过Method和目标类,拿到事务属性~~~
  3. // 比如我们的@Transaction是标注在方法上的,可议自定义方法级别的事务属性,用它就特别的方便~
  4. @Nullable
  5. TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass);
  6. }

这里有很多人不明白了,为何都给了Method,为啥还要传入Class呢?难道Method还不知道它所属的类???

这里做如下解释:

  1. method – 目前正在进行的方法调用
  2. targetClass – 真正要调用的方法所在的类

这里是有细微差别的:

  • method的所属类不一样是targetClass。比如:method是代理对象的方法,它的所属类是代理出来的类
  • 但是:targetClass一定会有一个方法和method的方法签名一样

通常情况下,method的所属类会是targetClass的某个祖先类或者实现的某个接口。(动态代理)

它的实现有多种:

0

TransactionAttributeSource一般都是作为TransactionInterceptor的一个属性被set进去,然后看看这个事务属性可以作用在不同的方法上面,实现不同方法的个性化定制~

(实际真正处理它的是父类TransactionAspectSupport,它会做匹配~~~~) 具体的在详解TransactionInterceptor的时候会讲述到

NameMatchTransactionAttributeSource

根据名字就能匹配,然后该事务属性就会作用在对应的方法上。比如下面例子:

  1. // 自定义配置一个事务拦截器(@Transaction注解也会使用此拦截器进行拦截)
  2. @Bean
  3. public TransactionInterceptor transactionInterceptor(PlatformTransactionManager transactionManager) {
  4. Map<String, TransactionAttribute> txMap = new HashMap<>();
  5. // required事务 适用于觉得部分场景~
  6. RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
  7. requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(RuntimeException.class)));
  8. requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
  9. txMap.put("add*", requiredTx);
  10. txMap.put("save*", requiredTx);
  11. txMap.put("insert*", requiredTx);
  12. txMap.put("update*", requiredTx);
  13. txMap.put("delete*", requiredTx);
  14. // 查询 使用只读事务
  15. RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
  16. readOnlyTx.setReadOnly(true);
  17. readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
  18. txMap.put("get*", readOnlyTx);
  19. txMap.put("query*", readOnlyTx);
  20. // 定义事务属性的source~~~ 此处使用它 也就是根据方法名进行匹配的~~~
  21. NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
  22. source.setNameMap(txMap);
  23. return new TransactionInterceptor(transactionManager, source);
  24. }

这个在我们基于XML的配置事务的时候,原理就是这样的~~

注意此处的匹配模式也是基于简单匹配的:PatternMatchUtils.simpleMatch。而非强大的正则匹配。底层getTransactionAttribute()时会根据不同的方法名,来返回不同的事务属性~~~

MethodMapTransactionAttributeSource

它的使用方式和NameMatchTransactionAttributeSource基本相同,但是有一个不同在于:

如果使用NameMatchTransactionAttributeSource配置属性源,比如get*配置为执行事务,那么所有的bean的get方法都会被加上事务,这可能不是我们想要的,因此对于自动代理,我们更好的选择是MethodMapTransactionAttributeSource,它需要指定需要事务化的完整类名和方法名

CompositeTransactionAttributeSource

它代表一种组合模式。

  1. // @since 2.0 它是Spring2.0后才推出来的
  2. public class CompositeTransactionAttributeSource implements TransactionAttributeSource, Serializable {
  3. private final TransactionAttributeSource[] transactionAttributeSources;
  4. public CompositeTransactionAttributeSource(TransactionAttributeSource... transactionAttributeSources) {
  5. Assert.notNull(transactionAttributeSources, "TransactionAttributeSource array must not be null");
  6. this.transactionAttributeSources = transactionAttributeSources;
  7. }
  8. // 这个实现方法也很容易。多个TransactionAttributeSource放在一起,只要任意一个匹配上就成
  9. // 备注:若匹配上多个,请注意先后顺序就成 这里面是数组 会保持和你放入的顺序一样~~~
  10. @Override
  11. @Nullable
  12. public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
  13. for (TransactionAttributeSource source : this.transactionAttributeSources) {
  14. TransactionAttribute attr = source.getTransactionAttribute(method, targetClass);
  15. if (attr != null) {
  16. return attr;
  17. }
  18. }
  19. return null;
  20. }
  21. }

MatchAlwaysTransactionAttributeSource

它是TransactionAttributeSource的一个最简单的实现,每次调用,都是返回相同的TransactionAttribute

当然它是可议set一个TransactionAttribute作为通用的事务属性的实现的

AnnotationTransactionAttributeSource

这个就是重点了,它是基于注解驱动的事务管理的事务属性源,和@Transaction相关,也是现在使用得最最多的方式。

它的基本作用为:它遇上比如@Transaction标注的方法时,此类会分析此事务注解,最终组织形成一个TransactionAttribute供随后的调用。

  1. public class AnnotationTransactionAttributeSource extends AbstractFallbackTransactionAttributeSource implements Serializable {
  2. // 这个是“向下兼容”,JavaEE提供的其余两种注解~~
  3. private static final boolean jta12Present; //JTA 1.2事务注解
  4. private static final boolean ejb3Present; //EJB 3 事务注解是
  5. static {
  6. ClassLoader classLoader = AnnotationTransactionAttributeSource.class.getClassLoader();
  7. jta12Present = ClassUtils.isPresent("javax.transaction.Transactional", classLoader);
  8. ejb3Present = ClassUtils.isPresent("javax.ejb.TransactionAttribute", classLoader);
  9. }
  10. // true:只处理public方法(基于JDK的代理 显然就只会处理这种方法)
  11. // falseprivate/protected等方法都会处理。 基于AspectJ代理得方式可议设置为false
  12. // 默认情况下:会被赋值为true,表示只处理public的方法
  13. private final boolean publicMethodsOnly;
  14. // 保存用于分析事务注解的事务注解分析器 这个注解分析的解析器是重点
  15. private final Set<TransactionAnnotationParser> annotationParsers;
  16. // 构造函数, publicMethodsOnly 缺省使用 true
  17. public AnnotationTransactionAttributeSource() {
  18. this(true);
  19. }
  20. public AnnotationTransactionAttributeSource(boolean publicMethodsOnly) {
  21. this.publicMethodsOnly = publicMethodsOnly;
  22. if (jta12Present || ejb3Present) {
  23. this.annotationParsers = new LinkedHashSet<>(4);
  24. this.annotationParsers.add(new SpringTransactionAnnotationParser());
  25. if (jta12Present) {
  26. this.annotationParsers.add(new JtaTransactionAnnotationParser());
  27. }
  28. if (ejb3Present) {
  29. this.annotationParsers.add(new Ejb3TransactionAnnotationParser());
  30. }
  31. }
  32. // 默认情况下,只添加Spring自己的注解解析器(绝大部分情况都实这里)
  33. else {
  34. this.annotationParsers = Collections.singleton(new SpringTransactionAnnotationParser());
  35. }
  36. }
  37. // 自己也可以指定一个TransactionAnnotationParser 或者多个也成
  38. public AnnotationTransactionAttributeSource(TransactionAnnotationParser annotationParser) { ... }
  39. public AnnotationTransactionAttributeSource(TransactionAnnotationParser... annotationParsers) { ... }
  40. public AnnotationTransactionAttributeSource(Set<TransactionAnnotationParser> annotationParsers) { ... }
  41. // 获取某个类/方法上的事务注解属性(属于 父类的抽象方法)
  42. @Override
  43. @Nullable
  44. protected TransactionAttribute findTransactionAttribute(Class<?> clazz) {
  45. return determineTransactionAttribute(clazz);
  46. }
  47. @Override
  48. @Nullable
  49. protected TransactionAttribute findTransactionAttribute(Method method) {
  50. return determineTransactionAttribute(method);
  51. }
  52. // 具体实现如下:
  53. // 分析获取某个被注解的元素(AnnotatedElement ),具体的来讲,指的是一个类或者一个方法上的事务注解属性。
  54. // 实现会遍历自己属性annotationParsers中所包含的事务注解属性分析器试图获取事务注解属性 所以主要还是依赖于TransactionAnnotationParser 去解析的
  55. @Nullable
  56. protected TransactionAttribute determineTransactionAttribute(AnnotatedElement element) {
  57. for (TransactionAnnotationParser annotationParser : this.annotationParsers) {
  58. TransactionAttribute attr = annotationParser.parseTransactionAnnotation(element);
  59. if (attr != null) {
  60. return attr;
  61. }
  62. }
  63. return null;
  64. }
  65. /**
  66. * By default, only public methods can be made transactional.
  67. */
  68. @Override
  69. protected boolean allowPublicMethodsOnly() {
  70. return this.publicMethodsOnly;
  71. }
  72. ...
  73. }

从源码中可议知道,真正提供给调用的getTransactionAttribute在父类中实现的:

AbstractFallbackTransactionAttributeSource

AbstractFallbackTransactionAttributeSource是接口TransactionAttributeSource的抽象实现,也是上面提到的工具类AnnotationTransactionAttributeSource的父类。

  1. public abstract class AbstractFallbackTransactionAttributeSource implements TransactionAttributeSource {
  2. // 针对没有事务注解属性的方法进行事务注解属性缓存时使用的特殊值,用于标记该方法没有事务注解属性
  3. // 从而不用在首次缓存在信息后,不用再次重复执行真正的分析 来提高查找的效率
  4. // 标注了@Transaction注解的表示有事务属性的,才会最终加入事务。但是,但是此处需要注意的是,只要被事务的Advisor切中的,都会缓存起来 放置过度的查找~~~~ 因此才有这个常量的出现
  5. private static final TransactionAttribute NULL_TRANSACTION_ATTRIBUTE = new DefaultTransactionAttribute() {
  6. @Override
  7. public String toString() {
  8. return "null";
  9. }
  10. };
  11. // 方法上的事务注解属性缓存,key使用目标类上的方法,使用类型MethodClassKey来表示
  12. // 这个Map会比较大,会被事务相关的Advisor拦截下来的方法,最终都会缓存下来。关于事务相关的Advisor,后续也是会着重讲解的~~~
  13. // 因为会有很多,所以我们才需要一个NULL_TRANSACTION_ATTRIBUTE常量来提高查找的效率~~~
  14. private final Map<Object, TransactionAttribute> attributeCache = new ConcurrentHashMap<>(1024);
  15. // 获取指定方法上的注解事务属性 如果方法上没有注解事务属性,则使用目标方法所属类上的注解事务属性
  16. @Override
  17. @Nullable
  18. public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
  19. // 如果目标方法是内置类Object上的方法,总是返回null,这些方法上不应用事务
  20. if (method.getDeclaringClass() == Object.class) {
  21. return null;
  22. }
  23. // 先看缓存里有木有,此处使用的非常经典的MethodClassKey作为Map的key
  24. Object cacheKey = getCacheKey(method, targetClass);
  25. TransactionAttribute cached = this.attributeCache.get(cacheKey);
  26. if (cached != null) {
  27. //目标方法上上并没有事务注解属性,但是已经被尝试分析过并且已经被缓存,
  28. // 使用的值是 NULL_TRANSACTION_ATTRIBUTE,所以这里再次尝试获取其注解事务属性时,直接返回 null
  29. if (cached == NULL_TRANSACTION_ATTRIBUTE) {
  30. return null;
  31. } else {
  32. return cached;
  33. }
  34. }
  35. // 缓存没有命中~~~~
  36. else {
  37. // 通过方法、目标Class 分析出此方法上的事务属性~~~~~
  38. TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
  39. // 如果目标方法上并没有使用注解事务属性,也缓存该信息,只不过使用的值是一个特殊值:
  40. if (txAttr == null) {
  41. this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE);
  42. }
  43. // 存在目标属性~ 就put到里面去。
  44. // 获取到methodIdentification 基本只为了输出日志~~~
  45. else {
  46. String methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass);
  47. if (txAttr instanceof DefaultTransactionAttribute) {
  48. ((DefaultTransactionAttribute) txAttr).setDescriptor(methodIdentification);
  49. }
  50. if (logger.isTraceEnabled()) {
  51. logger.trace("Adding transactional method '" + methodIdentification + "' with attribute: " + txAttr);
  52. }
  53. this.attributeCache.put(cacheKey, txAttr);
  54. }
  55. return txAttr;
  56. }
  57. }
  58. //查找目标方法上的事务注解属性 也是上面的核心方法
  59. @Nullable
  60. protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
  61. // 如果事务注解属性分析仅仅针对public方法,而当前方法不是public,则直接返回null
  62. // 如果是private,AOP是能切入,代理对象也会生成的 但就是事务不回生效的~~~~
  63. if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
  64. return null;
  65. }
  66. // 上面说了,因为Method并不一样属于目标类。所以这个方法就是获取targetClass上的那个和method对应的方法 也就是最终要执行的方法
  67. Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
  68. // 第一步:去找直接标记在方法上的事务属性~~~ 如果方法上有就直接返回(不用再看类上的了)
  69. // findTransactionAttribute这个方法其实就是子类去实现的
  70. TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
  71. if (txAttr != null) {
  72. return txAttr;
  73. }
  74. // 然后尝试检查事务注解属性是否标记在目标方法 specificMethod(注意此处用不是Method) 所属类上
  75. txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());
  76. if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
  77. return txAttr;
  78. }
  79. // 程序走到这里说明目标方法specificMethod,也就是实现类上的目标方法上没有标记事务注解属性(否则直接返回了嘛)
  80. // 如果 specificMethod 和 method 不同,则说明 specificMethod 是具体实现类的方法method 是实现类所实现接口的方法
  81. // 因此再次尝试从 method 上获取事务注解属性
  82. // 这也就是为何我们的@Transaction标注在接口上或者接口的方法上都是好使的原因~~~~~~~
  83. if (specificMethod != method) {
  84. // Fallback is to look at the original method.
  85. txAttr = findTransactionAttribute(method);
  86. if (txAttr != null) {
  87. return txAttr;
  88. }
  89. txAttr = findTransactionAttribute(method.getDeclaringClass());
  90. if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
  91. return txAttr;
  92. }
  93. }
  94. return null;
  95. }
  96. // 可议看到默认值是false 表示private的也是ok的
  97. // 但是`AnnotationTransactionAttributeSource`复写了它 可以由开发者指定(默认是true了)
  98. protected boolean allowPublicMethodsOnly() {
  99. return false;
  100. }
  101. }

从上文可以看出,真正把@Transaction注解变成一个TransactionAttribute类的是TransactionAnnotationParser,下面有必要来具体看看它

 

TransactionAnnotationParser

顾名思义,它是解析方法/类上事务注解的。

  1. // @since 2.5
  2. public interface TransactionAnnotationParser {
  3. @Nullable
  4. TransactionAttribute parseTransactionAnnotation(AnnotatedElement element);
  5. }

它支持上面说的到三个注解,分别对应三个实现类:JtaTransactionAnnotationParser、Ejb3TransactionAnnotationParser、SpringTransactionAnnotationParser

因为现在基本是Spring的天下了,因此本文只讲述SpringTransactionAnnotationParser,其它的雷同

SpringTransactionAnnotationParser

它专门用于解析Class或者Method上的org.springframework.transaction.annotation.Transactional注解的。

  1. // @since 2.5 此类的实现相对来说还是比较简单的
  2. public class SpringTransactionAnnotationParser implements TransactionAnnotationParser, Serializable {
  3. // 此方法对外暴露,表示获取该方法/类上面的TransactionAttribute
  4. @Override
  5. @Nullable
  6. public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
  7. AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(element, Transactional.class, false, false);
  8. if (attributes != null) {
  9. // 此处注意,把这个注解的属性交给它,最终转换为事务的属性类~~~~
  10. return parseTransactionAnnotation(attributes);
  11. }
  12. // 注解都木有,那就返回null
  13. else {
  14. return null;
  15. }
  16. }
  17. // 顺便提供的一个重载方法,可以让你直接传入一个注解
  18. public TransactionAttribute parseTransactionAnnotation(Transactional ann) {
  19. return parseTransactionAnnotation(AnnotationUtils.getAnnotationAttributes(ann, false, false));
  20. }
  21. // 这个简单的说:就是把注解的属性们 专门为事务属性们~~~~
  22. protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) {
  23. // 此处用的 RuleBasedTransactionAttribute 因为它可议指定不需要回滚的类~~~~
  24. RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();
  25. // 事务的传播属性枚举:内部定义了7种事务传播行为~~~~~
  26. Propagation propagation = attributes.getEnum("propagation");
  27. rbta.setPropagationBehavior(propagation.value());
  28. // 事务的隔离级别枚举。一共是4中,枚举里提供一个默认值: 也就是上面我们说的TransactionDefinition.ISOLATION_DEFAULT
  29. // 至于默认值是哪种隔离界别:这个具体的数据库有关~~~
  30. Isolation isolation = attributes.getEnum("isolation");
  31. rbta.setIsolationLevel(isolation.value());
  32. // 设置事务的超时时间
  33. rbta.setTimeout(attributes.getNumber("timeout").intValue());
  34. // 是否是只读事务
  35. rbta.setReadOnly(attributes.getBoolean("readOnly"));
  36. // 这个属性,是指定事务管理器PlatformTransactionManager的BeanName的,若不指定,那就按照类型找了
  37. // 若容器中存在多个事务管理器,但又没指定名字 那就报错啦~~~
  38. rbta.setQualifier(attributes.getString("value"));
  39. // rollbackFor可以指定需要回滚的异常,可议指定多个 若不指定默认为RuntimeException
  40. // 此处使用的RollbackRuleAttribute包装~~~~ 它就是个POJO没有实现其余接口
  41. List<RollbackRuleAttribute> rollbackRules = new ArrayList<>();
  42. for (Class<?> rbRule : attributes.getClassArray("rollbackFor")) {
  43. rollbackRules.add(new RollbackRuleAttribute(rbRule));
  44. }
  45. // 全类名的方式~~
  46. for (String rbRule : attributes.getStringArray("rollbackForClassName")) {
  47. rollbackRules.add(new RollbackRuleAttribute(rbRule));
  48. }
  49. // 指定不需要回滚的异常类型们~~~
  50. // 此处使用的NoRollbackRuleAttribute包装 它是RollbackRuleAttribute的子类
  51. for (Class<?> rbRule : attributes.getClassArray("noRollbackFor")) {
  52. rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
  53. }
  54. for (String rbRule : attributes.getStringArray("noRollbackForClassName")) {
  55. rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
  56. }
  57. // 最后别忘了set进去
  58. rbta.setRollbackRules(rollbackRules);
  59. return rbta;
  60. }
  61. }

通过这个parser就可议把方法/类上的注解,转换为事务属性,然后缓存起来。

这样方法在调用的时候,直接根据Method就能取到事务属性,从而执行不同的事务策略~~~

SavepointManager

管理事务savepoint的编程式API接口。

JDBC定义了SavePoint接口,提供在一个更细粒度的事务控制机制。当设置了一个保存点后,可以rollback到该保存点处的状态,而不是rollback整个事务。Connection接口的setSavepoint和releaseSavepoint方法可以设置和释放保存点。

  1. // @since 1.1
  2. public interface SavepointManager {
  3. Object createSavepoint() throws TransactionException;
  4. void rollbackToSavepoint(Object savepoint) throws TransactionException;
  5. void releaseSavepoint(Object savepoint) throws TransactionException;
  6. }

它的主要实现有如下:

0

TransactionStatus这个分支很重要,后面有着重分析。这里先看看JdbcTransactionObjectSupport这个实现

JdbcTransactionObjectSupport

  1. // @since 1.1 继承自SmartTransactionObject
  2. public abstract class JdbcTransactionObjectSupport implements SavepointManager, SmartTransactionObject {
  3. // 这是Spring定义的类,持有java.sql.Connection
  4. // 所以最支不支持还原点、创建还原点其实都是委托给它来的~
  5. @Nullable
  6. private ConnectionHolder connectionHolder;
  7. ...
  8. }

它也只是个抽象类,SmartTransactionObject接口相关的方法都没有去实现~~~~但是它的子类DataSourceTransactionObject有去实现的~

关于还原点的实现,整体上还是比较简单的,就是委托给Connection去做~



所属网站分类: 技术文章 > 博客

作者:我睡觉爱打呼噜

链接:http://www.javaheidong.com/blog/article/207421/49b2efe2e26da0e95936/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

5 0
收藏该文
已收藏

评论内容:(最多支持255个字符)