当前位置:网站首页>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
边栏推荐
猜你喜欢
‘npm‘不是内部或外部命令,也不是可运行的程序 或批处理文件
反思 | 事件总线的局限性,组件化开发流程中通信机制的设计与实现
Reflect on the limitations of event bus and the design and implementation of communication mechanism in component development process
学习笔记6-几种深度学习卷积神经网络的总结
h5本地存储数据sessionStorage、localStorage
Mysql 索引
SAP PI/PO Soap2Proxy 消费外部ws示例
Date对象(js内置对象)
Lead the industry trend with intelligent production! American camera intelligent video production platform unveiled at 2021 world Ultra HD Video Industry Development Conference
Nacos/sentinel网关限流和分组 (代码)
随机推荐
关于素数的不到100个秘密
SAP PI/PO rfc2RESTful 發布rfc接口為RESTful示例(Proxy間接法)
xdotool按键精灵
‘npm‘不是内部或外部命令,也不是可运行的程序 或批处理文件
Lead the industry trend with intelligent production! American camera intelligent video production platform unveiled at 2021 world Ultra HD Video Industry Development Conference
菜菜的刷题日记 | 蓝桥杯 — 十六进制转八进制(纯手撕版)附进制转换笔记
10.更新操作
[牛客挑战赛47]C.条件 (bitset加速floyd)
菜菜的并发编程笔记 |(五)线程安全问题以及Lock解决方案
获取字符格式的当前时间
LATEX使用
图论入门——建图
技能点挖坑
2.限定查询
Applet newline character \ nfailure problem resolution - Daily pit stepping
[CodeForces - 208E] Blood Cousins(k代兄弟问题)
Date对象(js内置对象)
学习笔记5-梯度爆炸和梯度消失(K折交叉验证)
[Ted series] how does a habit change my life
Applet Wx Previewmedia related problem solving - Daily stepping on the pit