每天学点Java之使用AspectJ实现AOP

使用AspectJ实现AOP

1.首先什么是AspectJ
  AspectJ是使用面向切面的一个框架 
  它扩展了Java语言(它本身也是一种语言)
  支持原生Java代码 有自己的编译器 将代码翻译成Java字节码文件
  是为了方便编写AOP代码而出现的
  使用AOP编程的三个重点 通知 切点 织入
2.使用AspectJ实现AOP方式一: xml配置完成AOP
  (1.创建通知类 添加需要的方法(前置 后置 环绕 Returning throwing)
  public class MyAdvice {
    // 前置通知
    public void before() {
        System.out.println("前置");
    }
    // 后置通知 始终会执行
    public void after() {
        System.out.println("后置");
    }
    // 环绕通知
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前");
        Object result = pjp.proceed();
        System.out.println("环绕后");
        return result;
    }
    // 后置 发生异常时不会执行
    public void returning() {
        System.out.println("After returning 后置");
    }
    // 发生异常
    public void throwing() {
        System.out.println("发生异常了");
    }
    (2.在配置文件中添加通知类的bean
    (3.添加<aop:config>添加子标签 
    <!-- 准备通知对象 -->
    <bean name="abc" class="com.lanou.advice.MyAdvice"></bean>
    <!-- 创建切入点 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.lanou.DaoImpl.*.*(..))" id="pc"/>
        <!-- 织入 -->
        <aop:aspect ref="abc">
            <!-- 按照顺序写方法 前 环绕 后 -->
            <aop:before method="before" pointcut-ref="pc"/>
            <aop:around method="around" pointcut-ref="pc"/>
            <aop:after method="after" pointcut-ref="pc"/>
            <aop:after-returning method="returning" pointcut-ref="pc"/>
            <aop:after-throwing method="throwing" pointcut-ref="pc"/>
        </aop:aspect>
    </aop:config>
3.使用注解配置完成AOP
    (1.创建通知类
    (2.添加@Aspect 设置通知类
    (3.创建切点方法
 // 将这个类作为通知类的注解
@Aspect 
@Component
public class MyAdvice_annotion {
    // 定义切入点
    @Pointcut("execution(* com.lanou.DaoImpl.*.*(..))")
    public void point() {}

    // 前置通知
    @Before("point()")
    public void before() {
        System.out.println("前置");
    }
    // 后置通知 始终会执行
    @After("point()")
    public void after() {
        System.out.println("后置");
    }
    // 环绕通知
    @Around("point()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前");
        Object result = pjp.proceed();
        System.out.println("环绕后");
        return result;
    }
    // 后置 发生异常时不会执行
    @AfterReturning("point()")
    public void returning() {
        System.out.println("After returning 后置");
    }
    // 发生异常
    @AfterThrowing("point()")
    public void throwing() {
        System.out.println("发生异常了");
    }
}
最后在Spring的配置文件中添加:
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
可以理解为:告诉Spring是使用@aspectJ和注解的方式实现AOP
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值