spring AOP切面开发 基于aspectJ框架切点的注解开发
基于annotation方案,注解开发
第一步:在配置文件中开启aspectj的注解
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
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">
<!-- 过滤可以使用注解的对象的类 -->
<context:component-scan base-package="cmo.demo"></context:component-scan>
<!-- 开启aspectj注解自动代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
第二步:
A,在通知类中用@component标签来声明一个通知
B,在通知类中用@Aspect来声明一个切面
C,在通知类的方法中设置要过滤后,增强的方法
@Pointcut("execution(* *Test(..))")
public void pointcutTest(){};
D,在通知类中用标签来设置环绕通知,前置通知等
@Before("pointcutTest()")
package cmo.demo.aspectj_annotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
//用注解声明是一个通知
@Component
@Aspect //声明这个类就是一个切面
public class CustomerServiceHelper {
@Pointcut("execution(* *Test(..))")
public void pointcutTest(){};
@Before("pointcutTest()")
public void before(JoinPoint jp) {
System.out.println("前置通知...");
}
@AfterReturning("pointcutTest()")
public void afterReturing(JoinPoint jp){
System.out.println("后置通知");
}
@Around("pointcutTest()")
public void around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("环绕方法+方法前");
Object proceed = pjp.proceed();
System.out.println("环绕方法+方法后");
}
@AfterThrowing(value="pointcutTest()",throwing="ex")
public void throwtest(JoinPoint jp, Throwable ex){
System.out.println("我要抛异常了"+ex);
}
@After("pointcutTest()")
public void after(JoinPoint jp){
System.out.println("最终会执行的方法");
}
}
将配置文件和通知类写完以后就可以实现以上功能了