pom.xml如下,需要引入spring-boot-starter-aop、spring-boot-starter-logging
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--日志-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--日志-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
</dependencies>
这里实现一个 只要方法上打了@Log注解,就会Aop拦截的案例
Log类定义如下:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 日志记录注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String Value() default "";
}
Aop类定义如下
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Date;
@Component
@Aspect
public class LogAopDemo {
private static final Logger logger = LoggerFactory.getLogger(LogAopDemo.class);
/**
* 切入点,对注解@Log进行拦截
*/
@Pointcut("@annotation(com.example.springboot3.Log)")
public void pointcut() {
}
/**
* 环绕proceedingJoinPoint
* @return
*/
@Around("pointcut()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object result = null;
//获取拦截的方法
MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
logger.info(String.format("【AOP】拦截方法:%s,开始时间:%s。", method.getName(), new Date().toString()));
logger.info("【AOP】Around(执行方法前):"+method.getName()+",传入参数:"+Arrays.asList(proceedingJoinPoint.getArgs()));
//拦截方法调用,此处可做一定的逻辑,如果是对权限进行过滤,没有权限不可调用,可return null
result = proceedingJoinPoint.proceed();
logger.info(String.format("【AOP】拦截方法:%s,结束时间:%s。", method.getName(), new Date().toString()));
return result;
}
}
这里定义好了之后,我们在某个方法上打下@Log注解,验证是否实现拦截
访问UserController的get方法后,可以从日志中看到拦截成功