首先自定義注解
@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";
}