10 - Spring5 学习笔记 - AOP 操作(AspectJ 注解、AspectJ 配置文件)

AOP 操作(准备)

1、Spring 框架一般都是基于 AspectJ 实现 AOP 操作

(1)什么是 AspectJ

  • AspectJ 不是 Spring 组成部分,是独立的 AOP 框架,一般把 AspectJSpring 框架一起使用,进行 AOP 操作。

2、基于 AspectJ 实现 AOP 操作

(1)基于 xml 配置文件

(2)基于注解方式实现(常用)

3、在项目工程引入 AOP 相关依赖
相关依赖相关依赖
导入的 jar 包

4、切入点表达式

(1)切入点表达式作用:直到对哪个类里面的哪个方法进行增强。
(2)语法结构:

execution([权限修饰符] [返回值类型] [类全路径] [方法名称] ([参数列表]))

例子:

com.tt.stu.dao.BookDao 类里面的 add 进行增强

execution(* com.tt.stu.dao.BookDao.add(…))
* :表示任意权限修饰符
… :表示方法中的参数

com.tt.stu.dao.BookDao 类里面的所有方法进行增强

execution(* com.tt.stu.dao.BookDao.(…)*)

com.tt.stu.dao 包里面所有类,类里面所有方法进行增强

execution(* com.tt.stu.dao.*.*(…))

AOP 操作(AspectJ 注解)

1、创建类,在类里面定义方法

// 被增强的类
public class User {
    public void add() {
        System.out.println("add ...");
    }
}

2、创建增强类(编写增强的逻辑)

(1)在增强类里面,创建方法,让不同方法代表不同通知类型。

// 增强的类
public class UserProxy {
    // 前置通知
    public void before() {
        System.out.println("before ...");
    }
}

3、进行通知的配置

(1)在 spring 配置文件中,开启注解扫描

<?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="com.tt.stu.spring5.aopanno"></context:component-scan>
</beans>

(2)使用注解创建 UserUserProxy 对象

在类中增加注解

@Component
public class User {
	// ...
}
// -------
@Component
public class UserProxy {
    // ...
}

(3)在增强类上面添加注解 @Aspect

在增强类,即 UserProxy 上,再添加注解。

@Component
@Aspect // 生成代理对象
public class UserProxy {
    // ...
}

(4)在 spring 配置文件中开启生成代理对象

在配置文件中增加配置

    <!--开启 Aspect 生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

4、配置不同类型的通知

(1)在增强类的里面,在作为通知方法上添加通知类型注解,使用切入点表达式配置。

// 增强的类
@Component
@Aspect 
public class UserProxy {
    // @Before 注解表示作为前置通知
    @Before(value = "execution(* com.tt.stu.spring5.aopanno.User.add(..))")
    public void before() {
        System.out.println("before ...");
    }
}

5、使用

public class TestAop {
    @Test
    public void testAopAnno() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        // id 默认为 类名,首字母变为小写
        User user = context.getBean("user", User.class);
        user.add();
    }
}

控制台打印结果如下:

before ...
add ...

我们再看看其他的注解怎么使用,以及执行的时机,我们在 Proxy 中添加如下代码

// 增强的类
@Component
@Aspect // 生成代理对象
public class UserProxy {
    // 前置通知
    // @Before 注解表示前置通知
    @Before(value = "execution(* com.tt.stu.spring5.aopanno.User.add(..))")
    public void before() {
        System.out.println("before ...");
    }

    // 最终通知
    // @After 注解表示最终通知,有没有异常都会通知
    @AfterReturning(value = "execution(* com.tt.stu.spring5.aopanno.User.add(..))")
    public void afterReturning() {
        System.out.println("afterReturning ...");
    }

    // 异常通知
    // @AfterThrowing 注解表示后置通知
    @AfterThrowing(value = "execution(* com.tt.stu.spring5.aopanno.User.add(..))")
    public void afterThrowing() {
        System.out.println("afterThrowing ...");
    }

    // 后置通知
    // @AfterReturning 注解表示后置通知
    @After(value = "execution(* com.tt.stu.spring5.aopanno.User.add(..))")
    public void after() {
        System.out.println("after ...");
    }
	
	// 环绕通知
	// @Around 注解表示环绕通知
    @Around(value = "execution(* com.tt.stu.spring5.aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前 ...");

        // 被增强的方法执行
        proceedingJoinPoint.proceed();

        System.out.println("环绕之后 ... ");
    }
}

调用测试方法,控制台输出结果:

环绕之前 ...
before ...
add ...
环绕之后 ... 
after ...
afterReturning ...

然后我们在被增强的方法中,增加一个异常,看看输出结果

    public void add() {
        int a = 10 / 0; // 增加异常
        System.out.println("add ...");
    }

调用测试方法,控制台输出结果:

环绕之前 ...
before ...
after ...
afterThrowing ...

java.lang.ArithmeticException: / by zero
	...

可以发现,少了 add 方法,环绕之后以及 afterReturning ,多了 afterThrowing

6、AspectJ 注解(细节问题)

(1)相同切入点抽取

我们刚刚会发现,每一个通知方法前面我们都用了一模一样的切入点表达式,即

 (value = "execution(* com.tt.stu.spring5.aopanno.User.add(..))")

我们可以将这些相同的切入点抽取出来,使代码更简洁

方法:我们在类中添加如下方法,并且使用 @Pointcut 注解。

public class UserProxy {

    // 相同切入点抽取
    @Pointcut(value = "execution(* com.tt.stu.spring5.aopanno.User.add(..))")
    public void pointDemo() {
    }
    
    @Before(value = "pointDemo()") // 调用方法
    public void before() {
        System.out.println("before ...");
    }
    // ...
}

这样我们可以把所有需要用到这个的切点,通过调用方法获取。

(2)有多个增强类对同一个方法进行增强,设置增强类的优先级,即谁先执行,谁后执行。

a. 在增强类上面添加注解 @Order (数字类型值),数值类型值越小,优先级越高。

我们对 UserProxy 设置为 3,对另一个增强类设置为 1,观察一下输出变化。

@Component
@Aspect // 生成代理对象
@Order(3) // 增加 Order = 3
public class UserProxy { ... }

@Component
@Aspect
@Order(1) // 设置为 1,比 UserProxy 小,优先级更高
public class PersonProxy {
    @Before(value = "execution(* com.tt.stu.spring5.aopanno.User.add(..))")
    public void before() {
        System.out.println("Person before ..");
    }
}

调用测试方法,控制台输出结果:

Person before ..
环绕之前 ...
before ...
add ...
环绕之后 ... 
after ...
afterReturning ...

在最前面多了 PersonProxy 里面的 before 方法

我们再调换一下它们的优先级,结果如下:

环绕之前 ...
before ...
Person before ..
add ...
环绕之后 ... 
after ...
afterReturning ...

可以看到,Person beforeUser before 之后。

(3)完全注解开发

这里面同样可以使用完全注解开发,而不用专门写一个配置去开启组件扫描,而是创建一个配置类。

// 配置类
@Configuration
@ComponentScan(basePackages = {"com.tt.stu"}) // 扫描的包
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}

修改测试代码,使用配置类加载:

    @Test
    public void testAopAnno2() {
        ApplicationContext context = new AnnotationConfigApplicationContext(ConfigAop.class);
        User user = context.getBean("user", User.class);
        user.add();
    }

一样可以正常使用,并且不用再使用配置文件了。

AOP操作(AspectJ 配置文件)不常用

1、创建两个类,增强类和被增强类,创建方法

// 被增强类
public class Book {
    public void buy() {
        System.out.println("buy ...");
    }
}
// 增强类
public class BookProxy {
    public void before() {
        System.out.println("before ...");
    }
}

2、在 spring 配置文件中创建两个类对象

    <!--创建对象-->
    <bean id="book" class="com.tt.stu.spring5.aopxml.Book"></bean>
    <bean id="bookProxy" class="com.tt.stu.spring5.aopxml.BookProxy"></bean>

3、在 spring 配置文件中配置切入点

<!--配置 aop 增强-->
    <aop:config>
        <!--切入点 -> 对类中的哪个方法进行增强-->
        <aop:pointcut id="p" expression="execution(* com.tt.stu.spring5.aopxml.Book.buy(..))"/>

        <!--配置切面 -> 新增加的增强方法,也就是增强类里面的增强方法
            aop:aspect:
                ref : 增强类
         -->
        <aop:aspect ref="bookProxy">
            <!--增强作用在具体的方法上
                aop:before : 前置通知
                    method : 哪个方法
                    pointcut-ref : 作用到哪个切入点上
            -->
            <aop:before method="before" pointcut-ref="p"></aop:before>
        </aop:aspect>
    </aop:config>

4、使用

    @Test
    public void testAopXml() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Book book = context.getBean("book", Book.class);
        book.buy();
    }

控制台输出结果:

before ...
buy ...

可以发现 beforebuy 之前,成功完成配置。

其余类型通知,同理配置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值