@Aspect注解是不能够通过类路径自动检测发现的,所以需要配合@Component注释或者在xml配置bean
一个类中的@Aspect注解标识它为一个切面,并且将自己从自动代理中排除(原因:不能陷入死循环)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MoocMethod {
String value();
}
@Service
public class MoocBiz {
@MoocMethod("MoocBiz save with MoocMethod.")
public String save(String arg) {
System.out.println("MoocBiz save : " + arg);
// throw new RuntimeException(" Save failed!");
return " Save success!";
}
}
@Component
@Aspect
public class MoocAspect {
//指定切点
@Pointcut("execution(* com.imooc.aop.aspectj.biz.*Biz.*(..))")
public void pointcut() {}
//winin:一个范围
@Pointcut("within(com.imooc.aop.aspectj.biz.*)")
public void bizPointcut() {}
@Before("pointcut()")
public void before() {
System.out.println("Before.");
}
pointcut()为存在@Pointcut的方法名,args(arg)传入参数属性名为arg,可以获得传入切点的参数内容,也可通过@annotation获得切点的注解内容
@Before("pointcut() && args(arg)")
public void beforeWithParam(String arg) {
System.out.println("BeforeWithParam." + arg);
}
@Before("pointcut() && @annotation(moocMethod)")
public void beforeWithAnnotaion(MoocMethod moocMethod) {
System.out.println("BeforeWithAnnotation." + moocMethod.value());
}
//可以获得切点的返回值
@AfterReturning(pointcut="bizPointcut()", returning="returnValue")
public void afterReturning(Object returnValue) {
System.out.println("AfterReturning : " + returnValue);
}
//可以获得切点抛出的异常信息
@AfterThrowing(pointcut="pointcut()", throwing="e")
public void afterThrowing(RuntimeException e) {
System.out.println("AfterThrowing : " + e.getMessage());
}
@After("pointcut()")
public void after() {
System.out.println("After.");
}
//around 第一个参数必须为ProceedingJoinPoint
@Around("pointcut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("Around 1.");
Object obj = pjp.proceed();
System.out.println("Around 2.");
System.out.println("Around : " + obj);
return obj;
}
}
Around 1.
Before.
BeforeWithAnnotation.MoocBiz save with MoocMethod.
BeforeWithParam.This is test.
MoocBiz save : This is test.
Around 2.
Around : Save success!
After.
AfterReturning : Save success!
<context:component-scan base-package="com.imooc.aop.aspectj"/>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>