九、基于注解的AOP开发

快速入门

  1. 创建目标接口和目标类(内部有切点)
  2. 创建切面类(内部有增强方法)
  3. 将目标类和切面类的对象创建权交给spring
  4. 在切面类中使用注解配置织入关系
  5. 在配置文件中开启组件扫描和AOP的自动代理
  6. 测试代码

applicationContext-anno.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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--  开启组件扫描  -->
    <context:component-scan base-package="com.example.anno"/>

    <!--  aop自动代理  -->
    <aop:aspectj-autoproxy/>

</beans>

注解配置AOP详解

注解通知的类型

通知的配置与法: @通知注解(“切点表达式”)
在这里插入图片描述

切点表达时的抽取

切面类MyAspect:

@Component("myAspect")
@Aspect //标注当前MyAspect是一个切面类
public class MyAspect {

	...
    //ProceedingJoinPoint:正在执行的连接点===切点
    //@Around("execution(* com.example.anno.*.*(..))")
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前增强......");
        Object proceed = pjp.proceed();//切点方法
        System.out.println("环绕后增强......");
        return proceed;
    }

    //@After("execution(* com.example.anno.*.*(..))")
    @After("MyAspect.pointcut()")
    public void after() {
        System.out.println("最终增强。。。。");
    }
    
    //定义切点表达式
    @Pointcut("execution(* com.example.anno.*.*(..))")
    public void pointcut(){}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值