前言
通过定义自定义注解,可以对代码进行特定的标注,然后可以利用反射等机制在运行时获取这些注解信息,并基于此进行特定的处理或行为,比如实现特定的逻辑、进行配置、提供额外的约束等。它为开发者提供了一种灵活、可扩展的方式来为代码添加自定义的描述和指示信息。
实现原理
自定义注解的原理主要包括以下几个方面:
- 定义:通过使用特定的语法来定义注解,包括注解的名称、属性等。
- 元数据存储:当编译器遇到自定义注解时,会将注解相关信息作为元数据与代码一起编译存储到字节码文件中。
- 反射获取:在运行时,通过反射机制可以获取到类、方法、字段等元素上所标注的注解对象,从而能够读取注解的属性值等信息。
- 处理逻辑:基于反射获取到的注解信息,可以编写相应的处理代码,来根据注解的指示执行特定的操作,如进行日志记录、权限验证、动态代理等。
实现
首先自定义一个注解
//指定该注解的保留策略为运行时
@Retention(RetentionPolicy.RUNTIME)
//指定该注解可应用于方法元素
@Target({ElementType.METHOD})
@Documented
public @interface WebLog {
/**
* 日志描述信息
*
* @return
*/
String description() default "";
}
在创建一个自己需要增强的类
@RestController
public class WebLogController {
@GetMapping("/log")
@WebLog
public String index() {
return "hello";
}
}
定义一个切面类
@Aspect
@Component
public class WebLogAspect {
private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
/** 换行符 */
private static final String LINE_SEPARATOR = System.lineSeparator();
/** 以自定义 @WebLog 注解为切点 */
@Pointcut("@annotation(com.shimu.ofsbl.log.WebLog)")
public void webLog() {}
/**
* 在切点之前织入
* @param joinPoint
* @throws Throwable
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 开始打印请求日志
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 获取 @WebLog 注解的描述信息
String methodDescription = getAspectLogDescription(joinPoint);
// 打印请求相关参数
logger.info("========================================== Start ==========================================");
// 打印请求 url
logger.info("URL : {}", request.getRequestURL().toString());
// 打印描述信息
logger.info("Description : {}", methodDescription);
// 打印 Http method
logger.info("HTTP Method : {}", request.getMethod());
// 打印调用 controller 的全路径以及执行方法
logger.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
// 打印请求的 IP
logger.info("IP : {}", request.getRemoteAddr());
// 打印请求入参
logger.info("Request Args : {}", new Gson().toJson(joinPoint.getArgs()));
}
/**
* 在切点之后织入
* @throws Throwable
*/
@After("webLog()")
public void doAfter() throws Throwable {
// 接口结束后换行,方便分割查看
logger.info("=========================================== End ===========================================" + LINE_SEPARATOR);
}
@Around("webLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
// 打印出参
logger.info("Response Args : {}", new Gson().toJson(result));
// 执行耗时
logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
return result;
}
/**
* 获取切面注解的描述
*
* @param joinPoint 切点
* @return 描述信息
* @throws Exception
*/
public String getAspectLogDescription(JoinPoint joinPoint)
throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
StringBuilder description = new StringBuilder("");
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description.append(method.getAnnotation(WebLog.class).description());
break;
}
}
}
return description.toString();
}
}
通过使用使用 @Aspect 注解来声明它是一个切面类,可以包含切点(Pointcut)、通知(Advice),之后使用 LoggerFactory 创建一个日志记录器 logger,用于记录日志信息