基於SSM利用SpringAOP切面及自定義註解 記錄每次操作記錄(操作日誌 同理)
阿新 • • 發佈:2019-01-06
前段時間根據業務需求要記錄每次操作時的相關資訊:本帖方式通過在SpringMVC中的Controller設定一個自定義註解類來進行對資料的接收,通過 SpringAOP切面來對接收的資料進行邏輯處理.
在事先根據業務需求建立的一個實體類(如: UploadCount)的基礎上:
1.首先springmvc.xml進行配置
2.根據業務需求建立自定義註解類<!-- 啟動AOP AspectJ註解自動代理 --> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 指定自定義註解類的路徑 及 配置在Controller上新增自定義註解來接收資料 --> <context:component-scan base-package="com.sl.api.common.util.aopUtils"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface UploadCountLogs {
String moduleName() default ""; //自定義引數
}
3.建立一個對接收到的資料進行邏輯處理的切點類
/** * 切點類 * @author shilei * @version 1.0 */ @Aspect @Component public class UploadCountLogsAspect{ //注入Service用於把上傳記錄的相關資料資訊儲存到資料庫 @Autowired private SchemeProposalsService schemeProposalsService; @Autowired private UserRedisUtils userRedisUtils; //本地異常日誌記錄物件 //private static final Logger logger = LoggerFactory.getLogger(UploadCountLogsAspect. class); //Controller層切點 @Pointcut("@annotation(com.sl.api.common.util.aopUtils.UploadCountLogs)") public void controllerAspect() { System.out.println("切入點..."); } /** * 前置通知 用於攔截Controller層 獲取記錄的操作資訊 * * @param joinPoint 切點 */ @Before("controllerAspect()") public void doBefore(JoinPoint joinPoint) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); User user = userRedisUtils.getUser(request); try { //具體業務邏輯 根據業務需求進行更改 UploadCount count = new UploadCount(); count.setTid(UUID.randomUUID().toString()); count.setModuleName(getControllerMethodDescription(joinPoint)[0]); count.setCreateUid(user.getUserId().toString()); count.setDeptId(user.getDeptId()); count.setDeptName(user.getDept()); //儲存資料庫 schemeProposalsService.addRecord(count); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取註解中對方法的描述資訊 用於Controller層註解 * * @param joinPoint 切點 * @return 方法描述 * @throws Exception */ public static String[] getControllerMethodDescription(JoinPoint joinPoint) throws Exception { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); String[] annos = {""}; for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { annos[0] = method.getAnnotation(UploadCountLogs.class).moduleName(); //具體的業務邏輯 根據業務需求進行更改 if(annos[0].equals("新聞")){ Random random = new Random(); int ran = random.nextInt(30); //[0,30) if (ran<10) { annos[0]="政務公示"; }else if (ran>=10 && ran<20) { annos[0]="政府輿情"; }else { annos[0]="新聞資料"; } } break; } } } return annos; } }
4.最後在Controller加上自定義註解類,完成!!!
@UploadCountLogs(moduleName="新聞")