1.在applicationContext.xml中开启annotation 声明
2. 被切的service 必须要实现接口。因为aop的实质其实是java的代理模式。
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
3.
package com.nql.aop;
import java.util.Arrays;
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.springframework.stereotype.Component;
import com.nql.vo.User;
@Component
@Aspect
public class ServiceAspect {
@Before(value="execution(* com.nql.server..*.*(..))")
public void serviceBefore(){
System.out.println("开启事务");
}
@After(value="execution(* com.nql.server..*.*(..))")
public void serviceAfter(){
System.out.println("提交事务");
}
@AfterReturning(value="execution(* com.nql.server..*.*(..))" ,argNames="ret",returning="ret")
public void serviceAfterReturning(Object val){
System.out.println("[aop]操作返回结果"+val);
}
@AfterThrowing(value="execution(* com.nql.server..*.*(..))" ,argNames="e",throwing="e")
public void serviceAfterThrowing(Exception exp){
System.out.println("[aop]异常"+exp.getMessage());
}
@Around(value="execution(* com.nql.server..*.*(..))")
public Object serviceAroud(ProceedingJoinPoint point) throws Throwable{
System.out.println("[aop]数据方法调用之前,参数"+Arrays.toString(point.getArgs()));
Object obj = point.proceed();//调用具体的真实操作
System.out.println("aop数据调用之后");
User user = new User();
user.setName("6666");
return user;
}
}