为了简化代码 所以使用AOP
以computer为例 怎么做:
建一个ComputerAop 写上@Aspect、配置一下、写@Before或@After或@AfterReturning或@AfterThrowing或@Around
配置:
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
引用的jar包:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.springframework.stereotype.Component;
1、@Before 目标方法执行之前
@Before("execution(public int com.jd.cumputer.service.ComputerService.*(..))")
public void before(JoinPoint jp) {
Object [] agrs = jp.getArgs();//获取列表的参数
Signature signature = jp.getSignature();//获取名字
String name = signature.getName();
System.out.println(this.getClass().getName()+":The "+name+" method begins.");
System.out.println(this.getClass().getName()+":Parameters of the div method: ["+agrs[0]+","+agrs[1]+"]");
}
2、@After目标方法执行完,无论目标方法有无异常都执行
@After("execution(public int com.jd.cumputer.service.ComputerService.*(..))")
public void after(JoinPoint jp) {
Signature signature = jp.getSignature();
String name = signature.getName();
System.out.println(this.getClass().getName()+":The "+name+" method ends.");
}
3、@AfterReturning目标方法返回结果,如果目标方法有异常则不执行
@AfterReturning(value= "execution(public int com.jd.cumputer.service.ComputerService.*(..))" ,returning="result")
public void afterReturning(JoinPoint jp,Object result) {
Signature signature = jp.getSignature();
String name = signature.getName();
System.out.println(this.getClass().getName()+":Result of the "+name+" method :" + result);
}
4、@AfterThrowing 如果目标方法有异常,抛出异常
@AfterThrowing(value= "execution(public int com.jd.cumputer.service.ComputerService.*(..))" ,throwing="e")
public void afterThrowing(JoinPoint jp,Exception e) {
System.out.println(e.getMessage());
}
5、@Around 可以实现以上四种方法
@Around(value= "execution(public int com.jd.cumputer.service.ComputerService.*(..))")
public Object around(ProceedingJoinPoint pjp) {
Object [] agrs = pjp.getArgs();
Signature signature =pjp.getSignature();
String name = signature.getName();
System.out.println(this.getClass().getName()+":The "+name+" method begins.");
System.out.println(this.getClass().getName()+":Parameters of the div method: ["+agrs[0]+","+agrs[1]+"]");
try {
Object result =null;
try {
Object object = pjp.getTarget();
result=pjp.proceed();
}finally {
System.out.println(this.getClass().getName()+":The "+name+" method ends.");
}
System.out.println(this.getClass().getName()+":Result of the "+name+" method :" + result);
return result;
}catch(Throwable e){
System.out.println(e.getMessage());
}
return -1;
}