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
}