spring boot自定义注解

1.添加依赖

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

2.创建@interface

关于@Target @Retention @Documented这几个注解可以查看一下这个文件
https://blog.youkuaiyun.com/liang100k/article/details/79515910

import java.lang.annotation.*;


@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD})
public @interface LoginAnno {
    /**
     * 在自定义注解中定义自己的参数 参数类型和参数名称
     * 日志类型
     * @return
     */
    String operationLogType();

    /**
     * 系统类型
     * @return
     */
    int systemType();

    /**
     * 操作描述
     * @return
     */
    String descript();
}

 

3.添加@Aspect 切面类

mport lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 描述:通过@Aspect注解使该类成为切面类
 */
@Aspect
@Component
@Slf4j
public class LoginAnnoImpl {

    @Pointcut("@annotation(com.ph.annotation.LoginAnno)")
    private void cut() {
    }

    /**
     *  功能:前置通知
     */
    @Before("cut()")
    public void  before(JoinPoint joinPoint){
        String operationLogType = "";
        int systemType = 0;
        String descript="";
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LoginAnno operationLog = method.getAnnotation(LoginAnno.class);
        if (operationLog != null) {
            //注解上的描述
            operationLogType = operationLog.operationLogType();
            systemType = operationLog.systemType();
            descript = operationLog.descript();
        }
         log.info("OperationLog ---> operationLogType:{},systemType:{},descript{}",operationLogType,systemType,descript);
    }
}

4.在方法上调用

 @LoginAnno(operationLogType = "发送消息",systemType = 1,descript = "发送消息")
  @RequestMapping("/test")
    public void testMethod(){
        //do something here
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值