前言
本章讲解注解的方式实现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.执行效果如下
其他通知的实现不再详述