zoukankan      html  css  js  c++  java
  • java 注解实现AOP

    首先自定义注解

    @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";
    }


  • 相关阅读:
    推荐一篇好文加上一些补充
    我也来写一个俄罗斯方块
    使用canvas绘制一个时钟
    断句:Store all parameters but the first passed to this function as an array
    Observer Pattern
    web worker 的 self
    练练断句
    as 什么意思?
    natively 在本地机器
    in mind (不是 切记 的意思)
  • 原文地址:https://www.cnblogs.com/bt2882/p/13825470.html
Copyright © 2011-2022 走看看