pom文件
<!-- 自定义注解-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
注解编写
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String param() default "";
}
切面类
@Aspect
@Component
public class MyAop {
private static final Logger logger = LoggerFactory.getLogger(MyAop.class);
@Around("@annotation(MyAnnotation)")
public Object method(ProceedingJoinPoint pjp) throws Throwable {
Signature signature = pjp.getSignature();
Object[] args = pjp.getArgs();
String argsStr = "";
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (i == 0) {
argsStr += "***参数为:" + args[i];
} else {
argsStr += "--&--" + args[i];
}
}
}
String s = signature.toString();
logger.info(s+"===Start" + argsStr);
try {
return pjp.proceed();
} finally {
logger.info(s+"===End");
}
}
}
在需要的地方添加注解
我是在这个controller上添加注解,每次访问的时候就会打印日志。
/**
* 测试redis
*/
@RequestMapping("/redisTest1")
@MyAnnotation
public void redisest1(String key, String value) {
redisUtil.addObject(key, value, 10000);
}
日志格式如下
2019-12-12 11:42:30.615 INFO 6776 --- [nio-8080-exec-5] com.qinghua.bird.config.logConfig.MyAop : void com.qinghua.bird.controller.CheckServer.redisest1(String,String)===Start***参数为:liqinghua--&--hahaha
2019-12-12 11:42:30.621 INFO 6776 --- [nio-8080-exec-5] com.qinghua.bird.config.logConfig.MyAop : void com.qinghua.bird.controller.CheckServer.redisest1(String,String)===End