• 自定义注解-基于AOP


    依赖:

          <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-aop</artifactId>
            </dependency>

    注解1(不带参数):

    /**
     * sea test 使用 AOP 自定义注解(不带参数)
     * @author sea
     *
     */
    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface SeaAnnotion {  
    } 

    注解2(带参数):

    /**
     * sea test 使用 AOP 自定义注解(带参数)
     * @author sea
     *
     */
    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface SeaAnnotion2 {  
       
        String title() default "";
    }

    配置切片:

    package com.sea.test.annotation.aop;
    
    import java.lang.reflect.Method;
    import java.util.Date;
    
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.Signature;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.reflect.MethodSignature;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    
    @Aspect
    @Component
    public class SeaAnnotionAOPs {
    
        private static Logger logger = LoggerFactory.getLogger(SeaAnnotionAOPs.class);
    
    
    //    @Around("execution(* com.sea.web.controller.UserController.*(..))") //com.icil.esolution.service.impl
    //    @Around("execution(* com.sea.test.pojo.*.*(..))&&@annotation(seaAnnotion)") 
        @Around("@annotation(seaAnnotion)")//作用到注释@seaAnnotion标记的方法上
        public Object handleSeaAnnotionAOPMethod(ProceedingJoinPoint pjp,SeaAnnotion  seaAnnotion) throws Throwable {
            System.err.println("7777777777777777777777777");
            System.err.println("7777777777777777777777777");
            System.err.println("7777777777777777777777777");
            long start = new Date().getTime();
            Object object = pjp.proceed(); // *********************************************
            
            System.err.println("7777777777777777777777777");
            System.err.println("7777777777777777777777777");
            System.err.println("7777777777777777777777777");
            String costTime = (new Date().getTime() - start) + "";
            String methodName = pjp.getSignature().getName();
            logger.info("*************** Run the  method --> {} total  cost  time  is {}  ms********************",
                    methodName, costTime);
    
            return object;
        }
        
        
        /**
         * 
         * @param pjp
         * @param seaAnnotion2 :带参数的注解
         * @return
         * @throws Throwable
         */
        @Around("@annotation(seaAnnotion2)")//作用到注释@seaAnnotion2标记的方法上
        public Object handleSeaAnnotionAOPMethod(ProceedingJoinPoint joinPoint,SeaAnnotion2  seaAnnotion2) throws Throwable {
            
            //获取注解属性值
            String title = seaAnnotion2.title();
            System.err.println("&&&&&&&&& title is "+title+" &&&&&&&&&&&&&&&&&");
            Object object = joinPoint.proceed(); // *********************************************
            
        
            //获取方法名
            String methodName = joinPoint.getSignature().getName();
            MethodSignature signature =  (MethodSignature)joinPoint.getSignature();
             //获取方法
             Method method = joinPoint.getTarget().getClass().getMethod(methodName, signature.getParameterTypes());
             
            return object;
        }
    
        
        
        
        
        private Method getMethod(ProceedingJoinPoint joinPoint) {
            //获取参数的类型
            Method method = null;
            try {
                Signature signature = joinPoint.getSignature();
                MethodSignature msig = null;
                if (!(signature instanceof MethodSignature)) {
                    throw new IllegalArgumentException("该注解只能用于方法");
                }
                msig = (MethodSignature) signature;
                method = joinPoint.getTarget().getClass().getMethod(msig.getName(), msig.getParameterTypes());
            } catch (NoSuchMethodException e) {
                logger.error("annotation no sucheMehtod", e);
            } catch (SecurityException e) {
                logger.error("annotation SecurityException", e);
            }
            return method;
        }
    
    
    
    }

    使用注解:

    @Component
    public class TestnonationClass {
    
        @SeaAnnotion
        public void  get() {
            System.err.println("hhahhahah");
            
            
        }
        
        
        
        @SeaAnnotion2(title="参数 title")
        public void  get2() {
            System.err.println("hhahhahah");
            
            
        }
        
        
    }

    test case:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = DemoApplication.class)
    public class AnnotionAOPTest {
        
    
    /**
     *注入Test的方法:否则容器加载不到,注解无效    
     */
    @Autowired
     private TestnonationClass testnonationClass;
     
    
    /**
     * 不带参数
     * @SeaAnnotion
     * @throws Exception
     */
     @Test
    public void testAOPAonotionNoparam() throws Exception {
         testnonationClass.get();
         System.err.println("hhh");
    }
    
     /**
      * 带参数
      * @throws Exception
       @SeaAnnotion2(title="sea  test aonotion with param")
      */
     @Test
    public void testAOPAonotionWithparam() throws Exception {
         testnonationClass.get2();
         System.err.println("hhh");
    }
     
     
     
     
    }
  • 相关阅读:
    搭建vue开发环境的步骤
    widow怎么结束某端口占用
    替换数据库表中某个代码段中某个字段的某一段字符串sql
    sql优化
    scssmap对象访问
    IntelliJ IDEA 和 webstorm更换主题
    css滚动条样式
    redis set
    【LeetCode】128. 最长连续序列
    第二章 模型评估
  • 原文地址:https://www.cnblogs.com/lshan/p/10999395.html
Copyright © 2020-2023  润新知