首先自定义注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface AopTest {
@AliasFor("cacheNames")
String[] value() default {};
@AliasFor("value")
String[] cacheNames() default {};
}
定义一个aop配置类
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
@Bean
public HelloAop getHelloAspct(){
return new HelloAop();
}
}
编写Aop类加上@Aspect注解
@Aspect
public class HelloAop {
// 切入点@annotation(net.crisps.cloud.example.annotation.AopTest) 扫描在我们加了自定义注解的地方执行
@Pointcut("@annotation(net.crisps.cloud.example.annotation.AopTest)")
public void testBefore(){
System.out.println("before------");
}
// @Before("@annotation(net.crisps.cloud.example.annotation.AopTest)")
// public void before(){
// System.out.println("before------");
// }
// @After("@annotation(net.crisps.cloud.example.annotation.AopTest)")
// public void after(){
// System.out.println("after------");
// }
// @AfterReturning(returning = "data", pointcut ="@annotation(net.crisps.cloud.example.annotation.AopTest)")
// public void afterReturning(JoinPoint joinPoint, Object data){
// System.out.println(data.toString());
// }
// 环绕切点执行此方法
@Around("testBefore()")
public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取到原本接口的方法,看是否需要调用接口的原本方法,不使用就直接返回了,不会执行原有接口的方法
CacheOperationInvoker cacheOperationInvoker = getCacheOperationInvoker(joinPoint);
cacheOperationInvoker.invoke();
System.out.println(Arrays.toString(joinPoint.getArgs()));
System.out.println("666666");
return "tz";
}
private CacheOperationInvoker getCacheOperationInvoker(ProceedingJoinPoint joinPoint) {
return () -> {
try {
return joinPoint.proceed();
} catch (Throwable ex) {
throw new CacheOperationInvoker.ThrowableWrapperException(ex);
}
};
}
}
然后直接使用就可以了注意要加上我们自定义的注解
@AopTest(value = "123")
public String testAop() {
System.out.println("执行aop方法");
return "testAop";
}