自定义注解

自定义注解可以标记在方法上或类上,用于在编译期或运行期进行特定的业务功能处理。在 Java 中,自定义注解使用 @interface 关键字来定义,它可以实现如:日志记录、性能监控、权限校验等功能。

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定义注解
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Target(ElementType.METHOD)
public @interface Demo {
    /**
     * 切面
     */
    @Aspect
    @Component
    class pickupDemo{

        /**
         * 切入点
         */
        @Pointcut("@annotation(com.speedaf.customer.order.web.provider.annotation.Demo)")
        public void logCut() {

        }

        /**
         * 后置通知  方法调用后触发
         */
        @After(value = "logCut()")
        public void after(){
            System.out.println("自定义注解");
        }

        /**
         * 异常通知
         */
        @AfterThrowing(value = "logCut()", throwing = "throwable")
        public void throwing(Throwable throwable) throws Throwable {
            throw throwable;
        }

    }
}

使用自定义注解

1     @Demo
2     @GetMapping("/demo")
3     public void demo(){}

 

posted @ 2025-02-19 17:47  客至在水一方  阅读(15)  评论(0)    收藏  举报