当前位置:网站首页>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
边栏推荐
- Mysql持久性的实现
- C语言的指针符号到底靠近变量类型还是变量名?
- 2. Restricted query
- 技能点挖坑
- 反思 | Android 音视频缓存机制的系统性设计
- Applet newline character \ nfailure problem resolution - Daily pit stepping
- Meishe technology launches professional video editing solution for desktop -- Meiying PC version
- [ACM-ICPC 2018 沈阳赛区网络预赛] J.Ka Chang (分块+dfs序)
- The difference between null and undefined
- 3.排序语句
猜你喜欢
随机推荐
(扩展)BSGS与高次同余方程
9.常用函数
公共依赖模块common的处理
【TED系列】一个习惯是如何改变我的一生
菜菜的并发编程笔记 |(九)异步IO实现并发爬虫加速
SAP TRANSLATE使用数据对象掩码示例
7. sub query
4.多表查询
快速下载vscode的方法
配置npm
NPM installation stepping pit
Visualization Road (IX) detailed explanation of arrow class
反思 | Android 音视频缓存机制的系统性设计
redis连接出错 ERR AUTH <password> called without any password configured for the default user.
页面实时显示当前时间
【TED系列】如何与内心深处的批评家相处?
反思|开启B站少女心模式,探究APP换肤机制的设计与实现
Nacos / sentinel gateway current limiting and grouping (code)
如何判断点是否在多边形内(包含复杂多边形或者多边形数量很多的情况)
快速傅里叶变换FFT简明教程









