1、首先创建一个新的 Maven 项目
引入依赖如下:
<---- 自动配置--->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<---- AOP starter--->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、定义注解
package com.ld.demo.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogAnnotation {
}
3、定义AOP,拦截注解了@LogAnnotation的方法
@Aspect
public class LogAnnotationAspect {
@Around("@annotation(logAnnotation)")
public Object logMethodExecution(ProceedingJoinPoint joinPoint, LogAnnotation logAannotation) throws Throwable {
MethodSignature methodSign = (MethodSignature) joinPoint.getSignature();
String methodName = methodSign.getDeclaringTypeName() + "." + methodSign.getName();
Object[] methodArgs = joinPoint.getArgs();
System.out.println(methodName);
System.out.println( Arrays.toString(methodArgs));
return joinPoint.proceed();
}
}
4、创建自动配置类
package com.ld.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.ld.demo.aspect.LogAnnotationAspect;
@Configuration
@EnableAspectJAutoProxy
public class LogStarterAutoConfiguration {
@Bean
LogAnnotationAspect logAnnotationAspect() {
return new LogAnnotationAspect();
}
}
5、配置 META-INF/spring.factories
resources下新建文件夹和文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.ld.demo.config.LogStarterAutoConfiguration
注意:以上是spring boot 2.x版本的方式,3.x是META-INF/spring/下面创建文件
org.springframework.boot.autoconfigure.AutoConfiguration.imports,文件内容是:
com.ld.demo.config.LogStarterAutoConfiguration
6、如何使用
工程打包,在其它工程引入对应的依赖,根据实际坐标引入
<dependency>
<groupId>XXXX</groupId>
<artifactId>XXXXXX</artifactId>
</dependency>
Controller请求方法上加注解
package com.ld.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ld.demo.annotation.LogAnnotation;
@RestController
@RequestMapping("/hello")
public class HelloController {
@LogAnnotation
@GetMapping("/world")
public String world() {
return "test";
}
}