Controller层设置切面的三种方式

[toc]

1.自定义PointcutAdvisor

1
2
3
4
5
6
7
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface AopAnnotation {
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class CustomizePointcutAdvisor extends DefaultPointcutAdvisor {

private static final Logger log = LoggerFactory.getLogger(CustomizePointcutAdvisor.class);

public CustomizePointcutAdvisor() {
Pointcut pointcut = this.buildPointcut();
Advice advice = this.buildAdvice();
this.setAdvice(advice);
this.setPointcut(pointcut);
}

private Advice buildAdvice() {
MethodInterceptor methodInterceptor = (methodInvocation) -> {
Method method = methodInvocation.getMethod();
Class<?> declaringClass = AopUtils.getTargetClass(methodInvocation.getThis());
Method specificMethod = AopUtils.getMostSpecificMethod(method, declaringClass);
long start = System.currentTimeMillis();

Object proceed;
try {
proceed = methodInvocation.proceed();
} catch (Throwable throwable) {
log.error("", throwable);
throw throwable;
} finally {
log.info("方法{}耗时:{}ms", specificMethod.getName(), (System.currentTimeMillis() - start));
}
return proceed;
};
return methodInterceptor;
}

private Pointcut buildPointcut() {
//ComposablePointcut 可组合的切点
Pointcut pointcut = Pointcuts.union(
//注解匹配切点
new AnnotationMatchingPointcut(AopAnnotation.class, true),
new AnnotationMatchingPointcut((Class) null, AopAnnotation.class));

return pointcut;
}
}

1
2
3
4
5
6
7
@Configuration
public class CustomizeAutoConfiguration {
@Bean
public CustomizePointcutAdvisor alertPointcutAdvisor() {
return new CustomizePointcutAdvisor();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RestController
@RequestMapping("/api/test")
public class AopTestController {

@GetMapping("/0")
public String test0() {
return "test0";
}

@AopAnnotation
@GetMapping("/1")
public String test1() {
return "test1";
}
}

2.@Aspect注解实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Aspect
@Component
public class AopAspect {

private static final Logger log = LoggerFactory.getLogger(AopAspect.class);

@Pointcut(value = "execution(public * com.zero.spingboot.aop.*Controller.*(..))")
public void pointcutClass() {
}

@Pointcut( value = "@annotation(com.zero.spingboot.aop.AopAnnotation)")
public void pointcutAnnotation() {
}

@Around("pointcutClass() && pointcutAnnotation()")
public Object executeAround(ProceedingJoinPoint pjp) throws Throwable {

long start = System.currentTimeMillis();

Object proceed;
try {
proceed = pjp.proceed();
} catch (Throwable throwable) {
log.error("", throwable);
throw throwable;
} finally {
log.info("方法{}耗时:{}ms", pjp.getSignature().getName(), (System.currentTimeMillis() - start));
}
return proceed;
}
}

3.HandlerInterceptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class CustomizerHandlerInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(CustomizerHandlerInterceptor.class);


@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String contextPath = request.getRequestURI();

if (handler instanceof HandlerMethod) {
AopAnnotation annotation = findAnnotation((HandlerMethod) handler, AopAnnotation.class);
if (annotation != null) {
logger.info("preHandle, url={}", contextPath);
}
}
return true;
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}

private static <A extends Annotation> A findAnnotation(HandlerMethod handler, Class<A> annotationType) {
if (handler == null) {
return null;
} else {
A annotation = handler.getBeanType().getAnnotation(annotationType);
if (annotation == null) {
annotation = handler.getMethodAnnotation(annotationType);
}

if (annotation == null) {
Class<?> clazz = handler.getBean().getClass();
if (clazz != null) {
annotation = clazz.getAnnotation(annotationType);
}
}

return annotation;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
public class WevMvcConfig extends WebMvcConfigurationSupport {

@Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);

CustomizerHandlerInterceptor pmsInterceptor = new CustomizerHandlerInterceptor();
registry
.addInterceptor(pmsInterceptor)
.addPathPatterns("/**");
}
}