配置
<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/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 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 扫描指定包下面的注解 -->
<context:component-scan base-package="com"/>
<!-- 开启使用注解完成织入 -->
<aop:aspectj-autoproxy/>
</beans>
通知类
@Component
@Aspect //代表这个类是一个通知类
public class MyAdvice {
@Pointcut("execution(* com.spring.aop.annotation.*ServiceImpl.*(..))") //切入点,匹配被切的类文件
public void pc(){
}
@Before("MyAdvice.pc()")
public void before(){
System.out.println("前置通知");
}
@Around("MyAdvice.pc()")
public Object around(ProceedingJoinPoint jp) throws Throwable{ //不放行方法就拦截掉了
System.out.println("环绕通知 前部分");
Object result = jp.proceed();//调用目标方法
System.out.println("环绕通知 后部分");
return result;
}
@AfterThrowing("MyAdvice.pc()")
public void afterException(){
System.out.println("异常拦截通知");
}
@After("MyAdvice.pc()")
public void after(){
System.out.println("后置通知--目标方法发生异常,还会执行");
}
@AfterReturning("MyAdvice.pc()")
public void afterReturn(){
System.out.println("后置通知 方法发生异常,不会执行");
}
}
评论区