Spring入门(七)Spring基于注解实现AOP

前言

      本章讲解注解的方式实现Spring的AOP

方法

1.概念

之前的无论是Schema-base方式还是AspectJ方式实现的AOP都是基于Spring配置文件进行实现的。我们知道,主流的操作现在都在往注解身上靠,那么AOP的实现也是存在注解方式哒!

2.在Spring配置文件中加入如下配置

<!-- 配置组件扫描,以便于告诉Spring哪里有注解 -->
<context:component-scan base-package="cn.edu.ccut"></context:component-scan>
<!-- 使用Cglib动态代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

3.配置前置通知

package cn.edu.ccut.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AspectAdvice {

    @Before("execution(* cn.edu.ccut.service.impl.StudentServiceImpl.*(..))")
    public void beforeAdvice(){
        System.out.println("我是前置通知!");
    }

    public void afterAdvice(){
        System.out.println("我是后置通知!");
    }

    public void exception(){
        System.out.println("我是异常通知!");
    }

    public Object aroundAdvice(ProceedingJoinPoint p) throws Throwable{
        System.out.println("环绕通知-前置");
        Object proceed = p.proceed();
        System.out.println("环绕通知-后置");
        return proceed;
    }
}

概念:

@Component:表示一个组件,即一个bean,等效于我们在xml中配置的bean标签

@Aspect:表示该类为一个切面类,等效于我们的aspect-config标签

@Before:表示前置通知,其参数为execution表达式

4.执行效果如下

其他通知的实现不再详述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值