依赖:

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

 

posted on 2019-06-10 18:15  lshan  阅读(520)  评论(0编辑  收藏  举报