Spring-AOP SpringBoot自动配置和启动Spring AOP

30 篇文章 0 订阅
3 篇文章 0 订阅

SpringBoot 会使用 @Conditional* 注解来进行判断是否需要自动启动 AOP,如果 classpath 下有 spring-aop 的 jar 和有 EnableAspectJAutoProxy 类等,它就会自动开启 spring-aop。并且此自动配置类还能通过 SpringBoot 的配置文件 application.properties 中配置的 AOP 相关属性进行选择,使用哪一种代理模式,非常智能。

package org.springframework.boot.autoconfigure.aop;

@Configuration
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {

	@Configuration
	@EnableAspectJAutoProxy(proxyTargetClass = false)
	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = true)
	public static class JdkDynamicAutoProxyConfiguration {

	}

	@Configuration
	@EnableAspectJAutoProxy(proxyTargetClass = true)
	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = false)
	public static class CglibAutoProxyConfiguration {

	}

}

总结

如果我们使用的 SpringBoot,只需要在 properties 文件中进行相关配置,或者不配置直接采用默认配置即可,我们不需要在启动类加上启动 Aop 的注解 EnableAspectJAutoProxy

如果我们使用的是非Springboot模式,我们需要在配置类上加上 EnableAspectJAutoProxy 此注解。

=============

@EnableAspectJAutoProxy

 

作用

  开启切面编程功能;

使用

   @Configuration
   @EnableAspectJAutoProxy
   public class AppConfig {


   }

原理

这里写图片描述

Bean定义扫描阶段

  1. 通过@Import导入AspectJAutoProxyRegistrar;
  2. 通过@Configuration解析添加AnnotationAwareAspectJAutoProxyCreator定义;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {

    /**
     * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
     * to standard Java interface-based proxies. The default is {@code false}.
     */
    boolean proxyTargetClass() default false;

    /**
     * Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
     * for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
     * Off by default, i.e. no guarantees that {@code AopContext} access will work.
     * @since 4.3.1
     */
    boolean exposeProxy() default false;

}

这里写图片描述

AnnotationAwareAspectJAutoProxyCreator解析

  AnnotationAwareAspectJAutoProxyCreator本质是BeanPostProcessor,容器启动过程中会调用registerBeanPostProcessors()进行BeanPostProcessor的创建和初始化;在bean创建和初始化阶段,符合条件的bean初始化完成后,通过postProcessAfterInitialization生成代理类,如下所示:
这里写图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值