手写Spring注解实现Spring AOP切面动态拦截
1.新建注解类命名为PointCutAddress
package com.map.common.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PointCutAddress {
}
这里要注意@Target,@Retention,@Documented在新加注解功能上的实际用途,不懂的可以百度其他博客,这里不做过多赘述。
2.创建切面Aspect类
package com.map.dotwith.map.aspect;
@Aspect
@Component
public class requestAspect {
// 配置织入点 添加刚才创建的注解的路径
@Pointcut("@annotation(com.map.common.annotation.PointCutAddress)")
public void logPointCut()
{
}
/**
* 处理完请求后执行
* 这里使用around
* 不同的功能使用不同的位置切入吧
* 但是要注意的是 @Before、@After、@Around三者传入的参数类型是不一样的
* @param joinPoint 切点
*/
@Around("logPointCut()")
public Object doAfterReturning(ProceedingJoinPoint joinPoint)
{
Object result = "";
try {
// 获取执行方法的返回数据
result = joinPoint.proceed();
// 这里做你的逻辑判断 修改执行方法得返回结果
if (**********){
result = "********";
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return result;
}
}
3.注解添加
这里很简单了,跟普通注解一样的,想在哪里切入就把注解添加在哪个方法上就行,调用这个方法就会进去切面执行切面内的逻辑。