公共依赖模块common的处理
公共依赖模块指的是多个模块之间共享的工具类、配置类、异常类、全局异常处理、全局返回值对象、公共依赖等。使用common模块应该尽可能的避免高耦合的情。下面我们来总结一下common模块的工作原理。
1. 打包方式
并不会使用spring-boot-maven-plugin打包插件来打包自己,而是使用Maven自带的打包方式,也就是:
<packaging>jar</packaging>
这种方式只会把类编译后生成的class文件打包在一个jar里,不会打包类包含的第三方依赖,并且在该项目里的pom.xml文件里面的声明的依赖也不会打包进来,这样就保证了common的轻量级。
2.配置文件
对于配置类,我们都会添加@Configuration这样的注解,只要我们类所在的包能被Spring扫描到,则我们的配置对象均会被Spring创建出来放在IOC容器里面。Spring默认的包扫描会扫面jar里面的配置类。
3.全局异常处理
全局异常处理使用@RestControllerAdvice 进行标记,它的工作方式也是将当前的类创建出来对象放在IOC里面
4.常用的常量
public class Constants {/*** UTF-8 字符集*/public static final String UTF8 = "UTF-8";/*** GBK 字符集*/public static final String GBK = "GBK";/*** http请求*/public static final String HTTP = "http://";/*** https请求*/public static final String HTTPS = "https://";/*** 成功标记*/public static final Integer SUCCESS = 200;/*** 失败标记*/public static final Integer FAIL = 500;/*** 验证码 redis key*/public static final String CAPTCHA_CODE_KEY = "captcha_codes:";/*** 验证码有效期(分钟)*/public static final long CAPTCHA_EXPIRATION = 2;}
5.统一的返回值对象
/*** 公共的返回值对象** @param <T>*/
public class R<T> implements Serializable {private static final long serialVersionUID = 1L;/*** 成功*/public static final int SUCCESS = Constants.SUCCESS;/*** 失败*/public static final int FAIL = Constants.FAIL;private int code;private String msg;private T data;public static <T> R<T> ok() {return restResult(null, SUCCESS, null);}public static <T> R<T> ok(T data) {return restResult(data, SUCCESS, null);}public static <T> R<T> ok(T data, String msg) {return restResult(data, SUCCESS, msg);}public static <T> R<T> fail() {return restResult(null, FAIL, null);}public static <T> R<T> fail(String msg) {return restResult(null, FAIL, msg);}public static <T> R<T> fail(T data) {return restResult(data, FAIL, null);}public static <T> R<T> fail(T data, String msg) {return restResult(data, FAIL, msg);}public static <T> R<T> fail(int code, String msg) {return restResult(null, code, msg);}private static <T> R<T> restResult(T data, int code, String msg) {R<T> apiResult = new R<>();apiResult.setCode(code);apiResult.setData(data);apiResult.setMsg(msg);return apiResult;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public T getData() {return data;}public void setData(T data) {this.data = data;}
}
6.公用的切面
web日志记录
@Aspect
@Component
@Order(1)
@Slf4j
public class WebLogAspect {@Pointcut("execution( * com.bjsxt.controller.*.*(..))")public void webLog() {}@Around(value = "webLog()")public Object recordWebLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {Object result = null;StopWatch stopWatch = new StopWatch(); // 创建计时器stopWatch.start(); // 开始计时器result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs()); // 不需要我们自己处理这个异常stopWatch.stop(); // 记时结束// 获取请求的上下文ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = requestAttributes.getRequest();// 获取登录的用户Authentication authentication = SecurityContextHolder.getContext().getAuthentication();// 获取方法MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();Method method = methodSignature.getMethod();// 获取方法上的ApiOperation注解ApiOperation annotation = method.getAnnotation(ApiOperation.class);// 获取目标对象的类型名称String className = proceedingJoinPoint.getTarget().getClass().getName();// 获取请求的url 地址String requestUrl = request.getRequestURL().toString();WebLog webLog = WebLog.builder().basePath(StrUtil.removeSuffix(requestUrl, URLUtil.url(requestUrl).getPath())).description(annotation == null ? "no desc" : annotation.value()).ip(request.getRemoteAddr()).parameter(getMethodParameter(method, proceedingJoinPoint.getArgs())).method(className + "." + method.getName()).result(request == null ? "" : JSON.toJSONString(request)).recodeTime(System.currentTimeMillis()).spendTime(stopWatch.getTotalTimeMillis()).uri(request.getRequestURI()).url(request.getRequestURL().toString()).username(authentication == null ? "anonymous" : authentication.getPrincipal().toString()).build();log.info(JSON.toJSONString(webLog, true));return result;}/*** {* "":value,* "":"value"* }** @param method* @param args* @return*/private Object getMethodParameter(Method method, Object[] args) {LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method);HashMap<String, Object> methodParameters = new HashMap<>();Parameter[] parameters = method.getParameters();if (args != null) {for (int i = 0; i < parameterNames.length; i++) {methodParameters.put(parameterNames[i], args[i] == null ? "" : JSON.toJSONString(args[i]));}}return methodParameters;}
}
全局web的异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(value = ApiException.class)public R handle(ApiException e) {if (e.getErrorCode() != null) {return R.fail(e.getErrorCode());}return R.fail(e.getMessage());}@ExceptionHandler(value = MethodArgumentNotValidException.class)public R handleValidException(MethodArgumentNotValidException e) {BindingResult bindingResult = e.getBindingResult();String message = null;if (bindingResult.hasErrors()) {FieldError fieldError = bindingResult.getFieldError();if (fieldError != null) {message = fieldError.getField() + fieldError.getDefaultMessage();}}return R.fail(message);}@ExceptionHandler(value = BindException.class)public R handleValidException(BindException e) {BindingResult bindingResult = e.getBindingResult();String message = null;if (bindingResult.hasErrors()) {FieldError fieldError = bindingResult.getFieldError();if (fieldError != null) {message = fieldError.getField() + fieldError.getDefaultMessage();}}return R.fail(message);}
}
公共依赖模块common的处理相关推荐
- 怎么让Go Modules使用私有依赖模块
Go语言官方的依赖包管理工具Go Modules已经发布很久,从1.14版本开始更是默认自动开启了Go Modules的支持,相信很多人公司里的项目都从go vendor.dep 之类的依赖管理切换到 ...
- Spring Cloud 升级之路 - 2020.0.x - 1. 背景知识、需求描述与公共依赖
1. 背景知识.需求描述与公共依赖 1.1. 背景知识 & 需求描述 Spring Cloud 官方文档说了,它是一个完整的微服务体系,用户可以通过使用 Spring Cloud 快速搭建一个 ...
- maven 打包命令,只编译选择模块及其依赖模块
当项目结构如下 --parent --admin --common --dal --service --web 如果你只想执行编译打包admin及其依赖模块,那么命令如下 mvn clean -U i ...
- ASP.NET中常用的几个李天平开源公共类LTP.Common,Maticsoft.DBUtility,LtpPageControl
ASP.NET中常用的几个开源公共类: LTP.Common.dll: 通用函数类库 源码下载 Maticsoft.DBUtility.dll 数据访问类库组件 源码下载 LtpPag ...
- #求教# 公共less模块中的背景图片地址应该怎么处理?
问题是这样的 ,我有一个公共组件模块,其中包含less写的样式而且样式中有url形式的背景图.其他项目在引用这个模块的时候,会引入这个less文件,项目使用webpack打包后会单独抽离出css样式文 ...
- Mozilla发布最大公共语音数据集Common Voice
近日,Mozilla发布了当前可使用的,规模最大的公共语音数据集Common Voice,数据集涵盖18种语言,由42000多名贡献者提供的近1400小时的语音数据构成. 文 / George Rot ...
- 系统中异常公共处理模块 in spring boot
最近在用spring boot 做微服务,所以对于异常信息的 [友好展示]有要求,我设计了两点: 一. 在业务逻辑代码中,异常的抛出 我做了限定,一般只会是三种: 1. OmcException // ...
- python依赖模块离线安装方法
一.方式一 1.依赖模块下载 下载需要的模块 :我这里下载openpyxl 模块(模块下载可以到python 官网上下载:PyPI · The Python Package Index)搜索openp ...
- LeetCode——1143. 最长公共子序列(Longest Common Subsequence)[中等]——分析及代码(Java)
LeetCode--1143. 最长公共子序列[Longest Common Subsequence][中等]--分析及代码[Java] 一.题目 二.分析及代码 1. 动态规划 (1)思路 (2)代 ...
最新文章
- MongoDB的查询整理
- python软件是免费的吗-python语言是免费还是收费的?
- SAP MES(manufacturing execution system)介绍
- linux 用户、群组及权限操作
- 第三讲 关系映射反演原则
- java证书已过期如何继续运行_过期证书上的Java trustmanager行为
- 安装Java (JDK16)
- 服装CAD软件测试初学者,CAD服装打版基础教程
- QT安装 and VS2019中安装QT插件
- 【办公-WORD】Word 背景颜色层次分析
- 中英文说明书丨CalBioreagents ACTH抗原抗体对
- 【012】基于51单片机的可燃气体报警装置proteus仿真与实物设计
- 在Python中以foo.bar.baz的方式访问嵌套dict中的内容
- 万国觉醒服务器维护,万国觉醒好像没看到1服怎么回事 官方关闭部分服务器公告[多图]...
- 深度学习——优化算法
- 攻防世界--no-strings-attached
- mysql命令创建用户_使用MySQL命令行新建用户并授予权限的方法
- chrome无法从该网站添加应用、扩展程序和用户脚本
- 分枝定界图解(含 Real-Time Loop Closure in 2D LIDAR SLAM论文部分解读及BB代码部分解读)
- matplotlib eps格栅化,透明度被改变的问题 pdf->eps