自定义注解-基于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");
}
 
 
 
 
}

 

转载于:https://www.cnblogs.com/lshan/p/10999395.html

好的,关于SpringBoot自定义注解AOP的问题,我可以为您提供一些基本的介绍和示例代码。 首先,AOP(Aspect-Oriented Programming)是一种编程范式,它可以在不修改业务逻辑代码的情况下,对应用程序进行横切关注点的切面处理。而Spring AOP作为Spring框架的一部分,提供了一种基于代理模式的AOP实现。 在使用Spring AOP的过程中,自定义注解可以作为切点表达式的一部分,通过对注解的解析,实现对被注解的方法或类的切面处理。下面是一个简单的示例代码,演示如何通过自定义注解实现对方法的AOP处理: 首先,定义一个自定义注解: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { String value() default ""; } ``` 然后,在需要被拦截的方法上添加该注解: ```java @Service public class MyService { @MyAnnotation("myAnnotation") public void doSomething() { System.out.println("do something..."); } } ``` 接下来,使用AspectJ的@Aspect注解定义一个切面类,并在该类中定义一个切点,用于匹配被@MyAnnotation注解的方法: ```java @Aspect @Component public class MyAspect { @Pointcut("@annotation(com.example.demo.annotation.MyAnnotation)") public void myAnnotationPointcut() {} @Before("myAnnotationPointcut()") public void beforeMyAnnotation() { System.out.println("before myAnnotation..."); } } ``` 最后,启动SpringBoot应用程序,调用MyService的doSomething方法,就可以看到输出结果: ```java before myAnnotation... do something... ``` 以上就是一个简单的SpringBoot自定义注解AOP的示例。通过使用自定义注解,可以更加方便地实现对应用程序的切面处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值