当前位置:网站首页>Processing of common dependency module
Processing of common dependency module
2022-04-23 07:41:00 【cqwoniu】
A common dependent module refers to a tool class shared among multiple modules 、 Configuration class 、 Exception class 、 Global exception handling 、 Global return value object 、 Public dependence, etc . Use common Modules should avoid high coupling as much as possible . Let's summarize common How the module works .
1. packaging
It doesn't use spring-boot-maven-plugin Package plug-ins to package yourself , But use Maven It's packed in its own way , That is to say :
<packaging>jar</packaging>
This method will only compile the class and generate class The files are packaged in a jar in , Third party dependencies contained in the class will not be packaged , And in the project pom.xml The dependencies declared in the file will not be packaged , That's the guarantee common Lightweight of .
2. The configuration file
For configuration classes , We all add @Configuration Such an annotation , As long as the package of our class can be Spring Scan to , Then our configuration objects will be Spring Create it and put it in IOC Inside the container .Spring The default package scan will scan the surface jar Inside the configuration class .
3. Global exception handling
Global exception handling uses @RestControllerAdvice marked , It also works by creating the current class and placing the object in IOC Inside
4. Common constants
public class Constants {
/** * UTF-8 Character set */
public static final String UTF8 = "UTF-8";
/** * GBK Character set */
public static final String GBK = "GBK";
/** * http request */
public static final String HTTP = "http://";
/** * https request */
public static final String HTTPS = "https://";
/** * Success mark */
public static final Integer SUCCESS = 200;
/** * Fail flag */
public static final Integer FAIL = 500;
/** * Verification Code redis key */
public static final String CAPTCHA_CODE_KEY = "captcha_codes:";
/** * The validity period of captcha ( minute ) */
public static final long CAPTCHA_EXPIRATION = 2;
}
5. Unified return value object
/** * Public return value object * * @param <T> */
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
/** * success */
public static final int SUCCESS = Constants.SUCCESS;
/** * Failure */
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. Common section
web logging
@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(); // Create timer
stopWatch.start(); // Start timer
result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs()); // We don't need to deal with this exception ourselves
stopWatch.stop(); // End of time
// Get the context of the request
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
// Get the logged in user
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// Access method
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = methodSignature.getMethod();
// On the method ApiOperation annotation
ApiOperation annotation = method.getAnnotation(ApiOperation.class);
// Get the type name of the target object
String className = proceedingJoinPoint.getTarget().getClass().getName();
// Obtain requested url Address
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;
}
}
overall situation web Exception handling
@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);
}
}
版权声明
本文为[cqwoniu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230622032220.html
边栏推荐
- 技术小白的第一篇(表达自己)
- The difference and application of VR, AR and MR, as well as some implementation principles of AR technology
- 反思 | 事件总线的局限性,组件化开发流程中通信机制的设计与实现
- Reflection on the systematic design of Android audio and video caching mechanism
- 1. View databases and tables
- 关于素数的不到100个秘密
- (扩展)BSGS与高次同余方程
- Mysql隔离级别
- 获取字符格式的当前时间
- 手游的热更方案与动态更新策略
猜你喜欢

Reflect on the limitations of event bus and the design and implementation of communication mechanism in component development process

安装配置淘宝镜像npm(cnpm)

直观理解熵

On BFC (block formatting context)

Educational Codeforces Round 81 (Rated for Div. 2)

保洁阿姨都能看懂的中国剩余定理和扩展中国剩余定理

Us photo cloud editing helps BiliBili upgrade its experience

组合数求解与(扩展)卢卡斯定理

SAP PI/PO rfc2Soap 发布rfc接口为ws示例
![[COCI]Lampice (二分+树分治+字符串哈希)](/img/7b/fe2a45d960a6d3eb7dc25200304adc.png)
[COCI]Lampice (二分+树分治+字符串哈希)
随机推荐
Design optimization of MySQL database
10.更新操作
Two threads print odd and even numbers interactively
菜菜的并发编程笔记 |(九)异步IO实现并发爬虫加速
直观理解熵
ESP32学习-GPIO的使用与配置
2022.3.14 Ali written examination
海康威视面经总结
On BFC (block formatting context)
[hdu6833]A Very Easy Math Problem(莫比乌斯反演)
Applet Wx Previewmedia related problem solving - Daily stepping on the pit
Discussion on arrow function of ES6
Date对象(js内置对象)
[牛客练习赛68]牛牛的粉丝(矩阵快速幂之循环矩阵优化)
[Ted series] how to get along with inner critics?
经典套路:一类字符串计数的DP问题
菜菜的并发编程笔记 |(五)线程安全问题以及Lock解决方案
Mysql隔离级别
VR、AR、MR的区别与应用,以及对AR技术的一些实现原理
redis连接出错 ERR AUTH <password> called without any password configured for the default user.