如果需要对业务方法中的参数和返回值做处理的情况下:
package com.chris.aop;
import org.springframework.stereotype.Service;
@Service("testService")
public class TestServiceBean {
public void save(){
System.out.println("save...");
}
public String update(String string){
System.out.println("update...");
return string;
}
public void add(String name,int age){
System.out.println("add..." +name+"-"+age);
}
}
切面类:
package com.chris.aop;
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//一定要将该类交给spring容器管理
@Aspect//声明该类为一个切面
public class InterceptorDemo {
//定义切入点(该切入点针对TestServiceBean中的所有方法进行拦截),切入点的语法下面介绍
@Pointcut("execution(* com.chris.aop.TestServiceBean.*(..))")
private void allMethod(){};//切入点的名称就是方法名
@Before("allMethod() && args(name,sex)")//定义切入点allMethod()中方法参数为(String,int)的方法的前置通知
public void doSomethingBefore(String name,int sex){
System.out.println("前置通知...");
}
@After("allMethod()")//定义切入点allMethod()的后置通知
public void doSomethingAfter(){
System.out.println("后置通知...");
}
@AfterReturning(pointcut="allMethod()",returning="update")//定义切入点allMethod()中返回值为String的方法的最终通知
public void doSomethingFinally(String update){
System.out.println("最终通知..."+update);
}
@AfterThrowing(pointcut="allMethod()",throwing="ex")//定义切入点allMethod()中抛出Exception异常的方法的异常通知
public void doSomethingInEx(Exception ex){
System.out.println("异常通知...");
}
@Around("allMethod()")//定义切入点allMethod()的环绕通知,环绕通知方法一定要按照下面的形式定义(只可以修改方法名和参数名)
public Object doSomethingAround(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("进入环绕通知...");
Object result = pjp.proceed();
System.out.println("退出环绕通知...");
return result;
}
}