优化这段代码: @AfterThrowing(value = "execution(* com.dianda.change.service..*.*(..))", throwing = "ex") public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) { try { logger.info("进入异常通知方法..."); Object targetObject = joinPoint.getTarget(); Signature signature = joinPoint.getSignature(); // System.out.println("ExceptionClassName={} ===" + ex.getClass().getName()); // // System.out.println("ExceptionClassName={} ===" + ex.getClass().getName()); Map<String, Object> map = new HashMap<>(); map.put("id", UUID.randomUUID().toString()); map.put("JKMC", targetObject.getClass().getName() + " signatureName=" + signature.getName()); map.put("CWMX", ex.getMessage()); map.put("ADDTIME", Format.getDateTime()); InsertParams insertParams = InsertParams.createInsertParams("T_RUN_ERROR_LOG"); insertParams.addParamsForMap(map); baseDaoComponent.insertDataByParams(insertParams); } catch (Exception e) { e.printStackTrace(); } // System.out.println("exception occurred at class "+targetObject.getClass().getName()+ // "\n signatureName="+signature.getName()); //// System.out.println("ExceptionClassName={}"+ ex.getClass().getName()); // System.out.println("message:{}"+ ex.getMessage()); }
时间: 2024-03-26 19:41:58 浏览: 66
spring_aop4.rar_aop4.com
这段代码可以进行如下优化:
1. 将 try-catch 语句块中的代码提取到一个方法中,避免重复代码:
```java
private void saveErrorLog(Object targetObject, Signature signature, Exception ex) {
try {
logger.info("进入异常通知方法...");
Map<String, Object> map = new HashMap<>();
map.put("id", UUID.randomUUID().toString());
map.put("JKMC", targetObject.getClass().getName() + " signatureName=" + signature.getName());
map.put("CWMX", ex.getMessage());
map.put("ADDTIME", Format.getDateTime());
InsertParams insertParams = InsertParams.createInsertParams("T_RUN_ERROR_LOG");
insertParams.addParamsForMap(map);
baseDaoComponent.insertDataByParams(insertParams);
} catch (Exception e) {
e.printStackTrace();
}
}
```
2. 使用 @Slf4j 注解代替手动创建 logger 对象,简化代码:
```java
@AfterThrowing(value = "execution(* com.dianda.change.service..*.*(..))", throwing = "ex")
public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) {
Object targetObject = joinPoint.getTarget();
Signature signature = joinPoint.getSignature();
saveErrorLog(targetObject, signature, ex);
}
```
通过上述优化,代码变得更加简洁易读,也更加易于维护。
阅读全文