功能:定义一个功能,使指定的方法执行前后输出日志信息。
1、定义一个注解,添加的方法上具有该功能,或者添加到类上,类下的所有方法都具有该功能
@Target( {ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAround {
}
2、实现PointCut
接口,找出标注注解的方法或类
// 这里是直接继承了一个便捷基类,实现 matches 方法
public class LogAroundPointcut extends StaticMethodMatcherPointcut {
@Override
public boolean matches(Method method, Class<?> targetClass) {
return AnnotatedElementUtils.hasAnnotation(targetClass, LogAround.class) ||
AnnotatedElementUtils.hasAnnotation(method, LogAround.class);
}
}
3、实现 Advice
,定义增强行为
// 这里继承了 MethodInterceptor,方法拦截。前后打印日志
public class LogAroundInterceptor implements MethodInterceptor {
@Nullable
@Override
public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable {
System.out.println("before method invoke log....");
Method method = invocation.getMethod();
Object[] args = invocation.getArguments();
Object target = invocation.getThis();
Object invoke = method.invoke(target, args);
System.out.println("after method invoke log....");
return invoke;
}
}
4、定义一个 Advisor
,把这两个组合起来,并添加到 Spring 中
@Component
public class LogAroundPointcutAdvisor extends AbstractPointcutAdvisor {
@Override
public Pointcut getPointcut() {
return new LogAroundPointcut();
}
@Override
public Advice getAdvice() {
return new LogAroundInterceptor();
}
@Override
public boolean isPerInstance() {
return false;
}
}
5、测试bean
@Component
public class AopDemo {
@LogAround
public static int sum(int i1, int i2) {
return i1 + i2;
}
}
6、测试结果
前后有打印日志,代理成功