目录
阅读本文之前建议先了解动态代理,可以参看我的另一篇博客 轻松理解 Java 静态代理/动态代理
小伙伴们有兴趣想了解内容和更多相关学习资料的请点赞收藏+评论转发+关注我,后面会有很多干货。我有一些面试题、架构、设计类资料可以说是程序员面试必备!所有资料都整理到网盘了,需要的话欢迎下载!私信我回复【000】即可免费获取

AOP (Aspect-Oriented Programming),即 面向切面编程, 它与 OOP (Object-Oriented Programming, 面向对象编程) 相辅相成, 提供了与 OOP 不同的抽象软件结构的视角.
在 OOP 中, 我们以类(class)作为我们的基本单元, 而 AOP 中的基本单元是 Aspect(切面)
AOP是 Spring 是最难理解的概念之一,同时也是非常重要的知识点,因为它真的很常用。
在面向切面编程的思想里面,把功能分为两种
在面向切面编程中,核心业务功能和周边功能是分别独立进行开发,两者不是耦合的;
然后把切面功能和核心业务功能 "编织" 在一起,这就叫AOP
AOP能够将那些与业务无关,却为业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来,便于减少系统的重复代码,降低模块间的耦合度,并有利于未来的可拓展性和可维护性。
进一步了解AOP之前,我们先来看看AOP中使用到的一些术语,以及AOP运行的流程。
上述的描述还是比较抽象的,配合下面的流程讲解以及例子,应该充分掌握这些概念了。
画了一张图,通过张图可以清晰地了解AOP的整个流程,以及上面各个术语的意义和关系。
图片的流程顺序基于Spring 5

不同版本的Spring是有一定差异的,使用时候要注意
举一个实际中的例子来说明一下方便理解:

房东的核心诉求其实就是签合同,收钱,浅绿部分都是次要的,交给中介就好。
不过有的人可能就有疑问了,让房东带着不是更好吗,租客沟通起来不是更轻松吗?为啥非要分成两部分呢?
那么请看下面这种情况

当我们有很多个房东的时候,中介的优势就体现出来了。代入到我们实际的业务中,AOP能够极大的减轻我们的开发工作,让关注点代码与业务代码分离!实现解藕!
用一个实际代码案例来感受一下
- @Component("landlord")
- public class Landlord {
-
- public void service() {
- System.out.println("签合同");
- System.out.println("收钱");
- }
- }
- @Component
- @Aspect
- class Broker {
- @Before("execution(* pojo.Landlord.service())")
- public void before(){
- System.out.println("带租客看房");
- System.out.println("谈钱");
- }
- @After("execution(* pojo.Landlord.service())")
- public void after(){
- System.out.println("给钥匙");
- }
- }
3.在 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:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
- <context:component-scan base-package="aspect" />
- <context:component-scan base-package="pojo" />
- <aop:aspectj-autoproxy/>
- </beans>
- public class Test {
- public static void main(String[] args) {
- ApplicationContext context =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- Landlord landlord = (Landlord) context.getBean("landlord", Landlord.class);
- landlord.service();
- }
- }
5.执行看到效果:
- 带租客看房
- 谈钱
- 签合同
- 收钱
- 给钥匙
这个例子中我们用到了@Before和@After两个注解,其实就是设置的前置通知和后置通知。
最后的结果似乎与我们之前图例中的顺序不同,给钥匙在收钱之后了,这个问题留到后面再解决,目前只需要简单感受一下aop的使用即可。
预告:这种情况下应该使用环绕通知来完成这个需求
目前使用注解的方式进行Spring开发才是主流,包括SpringBoot中,已经是全注解开发,所以我们采用@AspectJ的注解方式,重新实现一下上面的用例,来学习AOP的使用。

Spring 是方法级别的 AOP 框架,我们主要也是以某个类的某个方法作为连接点,另一种说法就是:选择哪一个类的哪一方法用以增强功能。
- @Component
- public class Landlord {
- public void service() {
- System.out.println("签合同");
- System.out.println("收钱");
- }
- }
我们在这里就选择上述 Landlord 类中的 service() 方法作为连接点。
选择好了连接点就可以创建切面了,我们可以把切面理解为一个拦截器,当程序运行到连接点的时候,被拦截下来,在开头加入了初始化的方法,在结尾也加入了销毁的方法而已,在 Spring 中只要使用 @Aspect 注解一个类,那么 Spring IoC 容器就会认为这是一个切面了:
- @Component
- @Aspect
- class Broker {
-
- @Before("execution(* com.aduner.demo03.pojo.Landlord.service())")
- public void before(){
- System.out.println("带租客看房");
- System.out.println("谈钱");
- }
-
- @After("execution(* com.aduner.demo03.pojo.Landlord.service())")
- public void after(){
- System.out.println("给钥匙");
- }
- }
切面的类仍然是一个 Bean ,需要 @Component 注解标注
在上面的注解中定义了 execution 的正则表达式,Spring会通过这个正则式去匹配、去确定对应的方法(连接点)是否启用切面编程
- execution(* com.aduner.demo03.pojo.Landlord.service())
依次对这个表达式作出分析:
每一个注解都重复写了同一个正则式,这显然比较冗余。为了克服这个问题,Spring定义了切点(Pointcut)的概念,切点的作用就是向Spring描述哪些类的哪些方法需要启用AOP编程,这样可以有效地降低代码的复杂度,而且有利于维护的方便。
- @Component
- @Aspect
- class Broker {
-
- @Pointcut("execution(* com.aduner.demo03.pojo.Landlord.service())")
- public void pointcut() {
- }
-
- @Before("pointcut()")
- public void before() {
- System.out.println("带租客看房");
- System.out.println("谈钱");
- }
-
- @After("pointcut()")
- public void after() {
- System.out.println("给钥匙");
- }
- }
- @Configuration
- @EnableAspectJAutoProxy
- @ComponentScan(basePackages = "com.aduner.demo03.*",
- excludeFilters = {@ComponentScan.Filter(classes = {Service.class})})
- public class AppConfig {
-
- }
- @Test
- void testAspect(){
- ApplicationContext ctx = new AnnotationConfigApplicationContext( AppConfig.class ) ;
- Landlord landlord=ctx.getBean(Landlord.class);
- landlord.service();
- ((ConfigurableApplicationContext)ctx).close();
- }
结果

现在我们来解决一下前面遗留的那个问题,收钱和给钥匙的问题。
我们需要的应该是给了钥匙之后再收钱,但是现在是反过来的。
要实现这个需求,用到环绕通知,这是 Spring AOP 中最强大的通知,集成了前置通知和后置通知。
环绕通知(Around)是所有通知中最为强大的通知,强大也意味着难以控制。一般而言,使用它的场景是在你需要大幅度修改原有目标对象的服务逻辑时,否则都尽量使用其他的通知。
环绕通知是一个取代原有目标对象方法的通知,当然它也提供了回调原有目标对象方法的能力。
- @Component
- public class Landlord {
- public void service(int steps) {
- if (steps == 1) {
- System.out.println("签合同");
- } else if(steps==2){
- System.out.println("收钱");
- }
- else {
- System.out.println("签合同");
- System.out.println("收钱");
- }
-
- }
- }
我们将service添加一个参数,第一步签合同,第二步收钱,如果没有制定第一步或者第二步,就一起执行。
- @Component
- @Aspect
- class Broker {
- @Pointcut("execution(* com.aduner.demo03.pojo.Landlord.service(*))")
- public void pointcut() {
- }
-
- @Around("pointcut()")
- public void around(ProceedingJoinPoint joinPoint) {
- System.out.println("带租客看房");
- System.out.println("谈价格");
-
- try {
- // joinPoint.proceed(); 这样就是执行原方法
- joinPoint.proceed(new Object[]{1}); //重新指定方法的参数
- System.out.println("交钥匙");
- joinPoint.proceed(new Object[]{2});
- } catch (Throwable throwable) {
- throwable.printStackTrace();
- }
- }
- }
- @Test
- void testAspect(){
- ApplicationContext ctx = new AnnotationConfigApplicationContext( AppConfig.class ) ;
- Landlord landlord=ctx.getBean(Landlord.class);
- landlord.service(0);
- ((ConfigurableApplicationContext)ctx).close();
- }
运行!成功!
- ……
- 带租客看房
- 谈价格
- 签合同
- 交钥匙
- 收钱
- ……
注意到切面编写中Around里面try中的joinPoint.proceed()方法
ProceedingJoinPoint对象是JoinPoint的子接口,该对象只用在@Around的切面方法中,添加了以下两个方法。
- Object proceed() throws Throwable //执行目标方法
- Object proceed(Object[] var1) throws Throwable //传入的新的参数去执行目标方法
前面的例子中我们显示把房东的工作分为了两步,然后在环绕通知中重新赋予参数并调用了两次,在两次中间插入了中介的工作。
实际开发中,上面这样的写法其实又会造成新的耦合,而且还会造成其他通知的混乱(调用了两次方法,其实会让有些通知返回两次)。
当然这只是一个例子,为了帮助更好地理解环绕通知。
Spring可以支持多个切面同时运行,如果刚好多个切面的切点相同,切面的运行顺序就是一个关键了。
默认情况下,切面的运行顺序是混乱的,如果需要指定切面的运行顺序,我们需要用到@Order注解
- @Component
- @Aspect
- @Order(1)
- public class FirstAspect {
- ……
- }
- --------------------
- @Component
- @Aspect
- @Order(2)
- public class SecondAspect {
- ……
- }
@Order注解中的值就是切片的顺序,但是他们不是顺序执行的而是包含关系。

小伙伴们有兴趣想了解内容和更多相关学习资料的请点赞收藏+评论转发+关注我,后面会有很多干货。我有一些面试题、架构、设计类资料可以说是程序员面试必备!所有资料都整理到网盘了,需要的话欢迎下载!私信我回复【000】即可免费获取
