Java自定义注解原理及实现 – 智云一二三科技 您所在的位置:网站首页 java自定义弹窗 Java自定义注解原理及实现 – 智云一二三科技

Java自定义注解原理及实现 – 智云一二三科技

2022-12-19 06:38| 来源: 网络整理| 查看: 265

一, 了解 注解 原理 元注解 元注解的作用就是注解其他注解,一般我们使用自定义注解时,就需要用元注解来标注我们自己的注解,一共有以下四个元注解

1.@Target: 说明了 annotation 被修饰的范围,可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标

例:@Target(ElementType.TYPE)

2.@Retention: 定义了该Annotation被保留的时间长短,有些只在源码中保留,有时需要编译成的class中保留,有些需要程序运行时候保留。即描述注解的 生命周期

例:@Retention(RetentionPolicy.RUNTIME) 1.RetentionPoicy.SOURCE:在源文件中有效(即源文件保留) 2.RetentionPoicy.CLASS:在class文件中有效(即class保留) 3.RetentionPoicy.RUNTIME:在运行时有效(即运行时保留)

3.@Documented: 它是一个标记注解,即没有成员的注解,用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如 javadoc 此类的工具文档化

4.@Inherited: 它也是一个标记注解,它的作用是,被它标注的类型是可被继承的,比如一个class被@Inherited标记,那么一个子类继承该class后,则这个annotation将被用于该class的子类。

注意:一个类型被@Inherited修饰后,类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation。

自定义注解

自定义注解格式:

public @interface 注解名 {定义体}

使用@interface定义一个注解,自动继承了java.lang.annotation.Annotation接口,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。可以通过default来声明参数的默认值。

注解参数的可支持数据类型: 1.所有基本数据类型(int,float,boolean,byte,double, char ,long,short) 2.String类型 3.Class类型 4.enum类型 5.Annotation类型 6.以上所有类型的数组

定义注解成员的注意点: 第一,只能用public或默认(default)这两个访问权修饰.例如,String value();这里把方法设为defaul默认类型;

二, 自定义注解(根据实际应用自定义注解打印每个接口的请求日志)

自定义注解的场景有很多,比如登录、权限拦截、日志、以及各种框架, 我们这里以请求日志为例

import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 操作日志注解 * * @Filename: ActionLog.java * @Author: zhangshuai * Version: 1.0 */@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface ActionLog { /** * 业务模块名称 * * @return */ String module(); /** * 操作名称 * * @return */ String action(); /** * 控制器出现异常的时候返回消息 * 此时会打印错误日志 * * @return */ String error() default "操作失败"; }

日志注解拦截器

/** * 操作日志切面拦截 * * @Filename: WebLogAspect.java * @Author: zhangshuai * Version: 1.0 */@Slf4j @Aspect @Component public class WebLogAspect { private static final String SPLIT_STRING_M = "="; private static final String SPLIT_STRING_DOT = ", "; @Pointcut("@annotation(com.paat.common.annotation.ActionLog)") public void webLog() { } /** * 环绕 */ @Around("webLog() && @annotation(actionLog)") public Object doAround(ProceedingJoinPoint proceedingJoinPoint, ActionLog actionLog) { Stopwatch stopwatch = Stopwatch.createStarted(); try { // 开始打印请求日志 HttpServletRequest request = getRequest(); String urlParams = get Request Params(request); IndexUserVO indexUserVO = BaseController.getIndexUser(); Integer loginUserId = null != indexUserVO ? indexUserVO.getUserId() : null; String tel = null != indexUserVO ? indexUserVO.getTel() : null; Integer userType = null != indexUserVO ? indexUserVO.getUserType() : null; // 打印请求 url log.info("请求 URI : {}\t{}", request.getMethod(), request.getRequestURI()); log.info("访问者IP: {}", IpHelper.getIpAddr(request)); log.info("请求轨迹: {}-{}-{} 在操作 [{}-{}]", loginUserId, tel, userType, actionLog.module(), actionLog.action()); if (StringUtils.isNotEmpty(urlParams)) { log.info("请求参数: {}", urlParams); } String body = (String) request.getAttribute(REQUEST_BODY_ATTR_KEY); if (StringUtils.isNotEmpty(body)) { log.info("请求主体: {}", body); } stopwatch = Stopwatch.createStarted(); Object result = proceedingJoinPoint.proceed(); this.printTimes(stopwatch, result); return result; } catch (TipException e) { BaseResponse response = Response.fail(e.getMessage()).build(); this.printTimes(stopwatch, response); return response; } catch (BizException e) { if (e.getCause() != null) { log.error("【{}-{}】 发生异常: ", actionLog.module(), actionLog.action(), e); } BaseResponse response = Response.fail(e.getMessage()).build(); this.printTimes(stopwatch, response); return response; } catch (Throwable e) { log.error("【{}-{}】 发生异常: ", actionLog.module(), actionLog.action(), e); String error = actionLog.error(); if (StringUtil.isEmpty(error)) { error = actionLog.action() + "失败"; } BaseResponse response = Response.fail(error).build(); this.printTimes(stopwatch, response); return response; } } /** * 获取请求地址上的参数 * * @param request * @return */ private String getRequestParams(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); Enumeration enu = request.getParameterNames(); //获取请求参数 while (enu.hasMoreElements()) { String name = enu.nextElement(); sb.append(name).append(SPLIT_STRING_M) .append(request.getParameter(name)); if (enu.hasMoreElements()) { sb.append(SPLIT_STRING_DOT); } } return sb.toString(); } private HttpServletRequest getRequest() { ServletRequestAttributes attributes = ( Servlet RequestAttributes) RequestContextHolder.getRequestAttributes(); return attributes.getRequest(); } private void printTimes(Stopwatch stopwatch, Object result) { log.info("响应结果: {}", getMaxBody(JSON.toJSONString(result))); log.info("执行耗时: {}ms\n", stopwatch.elapsed(TimeUnit.MILLISECONDS)); } }

我们只需在Controller上的方法贴上自定义注解 @ActionLog(module = “支付模块”, action = “支付接口”) 每次调用带有次注解的方法即可打印我们的请求日志信息



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有