1、自定义注解类
import java.lang.annotation.*;
//注解信息会被添加到Java文档中
@Documented
//注解的生命周期,表示注解会被保留到什么阶段,可以选择编译阶段、类加载阶段,或运行阶段
@Retention(RetentionPolicy.RUNTIME)
//注解作用的位置,ElementType.METHOD表示该注解仅能作用于方法上
@Target(ElementType.METHOD)
public @interface ZxyLog {
String value() default "";
}
2、切面类
import java.util.Arrays;
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.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
@Aspect
public class ZxyLogAspect {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* 其中@Pointcut声明了切点(这里的切点是我们自定义的注解类),
* @Before声明了通知内容,在具体的通知中,我们通过@annotation(logger)拿到了自定义的注解对象,
* 所以就能够获取我们在使用注解时赋予的值了。
*/
@Pointcut("@annotation(com.up.springboot.anno.ZxyLog)")
private void pointcut() {}
@Before("pointcut() && @annotation(logger)")
public void before(JoinPoint joinPoint,ZxyLog logger) {
//类名
String clsName=joinPoint.getSignature().getDeclaringType().getSimpleName();
//方法名
String modName= joinPoint.getSignature().getName();
//参数
Object[] args = joinPoint.getArgs();
StringBuffer result = new StringBuffer();
result.append("["+clsName+"]");
result.append("["+modName+"]");
Arrays.stream(args).forEach(arg->{
try {
result.append("["+OBJECT_MAPPER.writeValueAsString(arg)+"]");
} catch (JsonProcessingException e) {
}
});
System.out.println(result.toString());
}
}
3、使用
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.up.springboot.anno.ZxyLog;
import com.up.springboot.common.ReturnItemUtils;
import com.up.springboot.common.pojo.ReturnItem;
/**
* Created by xinye on 2019/10/16.
*
*/
@SuppressWarnings("rawtypes")
@RestController
@RequestMapping("/pernas/test")
public class TestController {
@SuppressWarnings("finally")
@ZxyLog()
@GetMapping("/test")
public ReturnItem select(@RequestParam(name = "token") String token,
@RequestParam(name = "aaa",required = false) String aaa,
@RequestParam(name = "bbb",required = false) Integer bbb) {
try {
System.out.println("======ing.aaa:"+aaa);
}catch (Exception e) {
}finally {
return ReturnItemUtils.newSuccessReturnItem();
}
}
}
4、输出
[TestController][select]["68f033399105b740b3537bcdc8b87971"]["111"][222]
======ing.aaa:111
依赖jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
参见:
spring 源码分析--之注解扫描原理www.jianshu.com![4c44680058c1a913bead14623e23726a.png](https://img-blog.csdnimg.cn/img_convert/4c44680058c1a913bead14623e23726a.png)