AOP注解方式
首先在入口类中开启注解、开启扫描路径,然后开启对AOP相关注解的相关处理:
@Configuration
@ComponentScan(basePackages = "com.lanou3g.spring.simple.say")
@EnableAspectJAutoProxy
public class AppByAnnotation {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppByAnnotation.class);
ISayHello hello = ctx.getBean(ISayHello.class);
hello.sayHello("JinSaiSai");
}
}
写一个需要切入的类:
@Component
public class SayHelloImpl implements ISayHello {
@Override
public void sayHello() {
log.info("hello world!");
}
@Override
public void sayHello(String name) {
log.info("hello, " + name);
}
}
单独定义一个类用一个方法定义系统中所有用到的切入点表达式:
public class GlobalPointcut {
@Pointcut("execution(* com.lanou3g.spring.simple.say..*.*(..))")
public void say_all_method() {}
}
定义一个切面,负责收集方法调用的入参、出参(返回值):
public class MethodInOutAspect {
@Around("com.lanou3g.spring.GlobalPointcut.say_all_method()")
public Object aroundM(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
log.debug("[aroundM] "+methodName+"("+ Arrays.toString(args) +") 开始执行");
Object retuVal = joinPoint.proceed();
log.debug("[aroundM] "+methodName+"("+ Arrays.toString(args) +") 返回值: " + retuVal);
return retuVal;
}
@AfterReturning(pointcut = "com.lanou3g.spring.GlobalPointcut.say_all_method()", returning = "ret")
public Object afterRM(Object ret) {
log.debug("[afterRM] 返回值: " + ret);
return ret;
}
}