Spring Boot里AOP是如何工作的(一)?

相信Java服务端的小伙伴都听说并且使用过AOP(面向切面编程),本期从源代码的角度分析Spring Boot是如何实现AOP的。

本文基于spring-boot 2.4.5

Spring AOP中的重要概念

Spring风靡全球的一个重要原因是完善的文档和活跃的社区。Spring AOP官方文档详细地介绍了AOP中的重要概念,11. Aspect Oriented Programming with Spring。本期重点提一下以下几点:

  1. Spring AOP是纯Java实现,没有编译时织入(区别于AspectJ)
  2. Spring AOP仅支持方法运行的join points(区别于AspectJ),并且仅限于Spring Bean的方法。
  3. Spring AOP是基于代理的(proxy-based),默认使用dynamic proxy(interface),也支持CGLIB(class)。
  4. Spring Boot里面的Aspect注解并不是说Spring AOP是基于AspectJ,Spring AOP只是使用了AspectJ里pointcut解析和匹配。

AOP配置

AOP生效,需要以下几个配置,接下来结合源代码分析每一个配置做了什么。

1 )配置maven依赖


            org.springframework.boot
            spring-boot-starter-aop
 

2)定义带@Aspect注解的Bean

@Aspect
@Component
public class DistributorServiceAop {
}

3)声明join point和advice

@Around("execution( double  com.lin.distributor.service.DistributorService.getRandom() )")
    public Object randomAdvice(ProceedingJoinPoint point){
        return 1.0;
    }

starter-aop做了啥

要使用AOP,需要引入starter-aop这个依赖。但starter-aop的源代码里面没有spring.factories,仅引入了aspectjweaver和spring-aop,那是如何实现starter呢?

Spring Boot里AOP是如何工作的(一)?

在Spring boot里,有一个spring-boot-autoconfig,里面定义了非常多的auto config,当然包括AOP的AopAutoConfiguration,引入aspectjweaver,意味着Advice在类路径上,AspectJAutoProxyingConfiguration将会激活。根据ConditionalOnProperty的条件,JdkProxy和CglibProxy只有一个会激活,但是它们俩都会引入EnableAspectJAutoProxy,这个注解将在下篇文章进行介绍。

@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass(Advice.class)
	static class AspectJAutoProxyingConfiguration {

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

		}

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

		}
	}
展开阅读全文

页面更新:2024-04-24

标签:都会   切面   下篇   注解   本期   源代码   服务端   路径   活跃   角度   区别   定义   概念   文档   方法

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top