日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringAOP xml 方式和注解简单实现日志处理

發布時間:2023/12/10 javascript 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringAOP xml 方式和注解简单实现日志处理 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.首先是用注解方式捕捉Controller 層異常:

首先是引入aop 依賴的jar

<!-- Spring AOP 日志管理需要導入的包 --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.8.13</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.13</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>4.3.18.RELEASE</version></dependency>

其次是在applicationg.xml spring 容器中加入 aop 配置

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:aop="http://www.springframework.org/schema/aop" ....xsi:schemaLocation="... http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd

?在application 添加spring配置代理

<!-- proxy-target-class="true"配置使Spring采用CGLIB代理 proxy-target-class="false" 配置使Spring采用JDK代理--><!-- 開啟@aspectJ切面注解器 默認是flase --><aop:aspectj-autoproxy />

添加自定義注解:?

package com.buDun.test.annotation;import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME) //@Target({ElementType.METHOD,ElementType.FIELD}) @Target(ElementType.METHOD) @Documented public @interface Loggable {/**Insert,Update,Delete,Select */String optType() default "";/** 描述*/String describe() default "";/**模塊 */String module() default ""; }

參考:http://mini.eastday.com/bdmip/180411141722960.html

定義一個切面:

注意:@AfterReturning 注解args參數中一定有,returning="retVal" 并且注解參數名稱 和方法參數名稱相同

? ? ?@AfterThrowing? 注解也是:注解args參數一定有throwing="ex"? 并且注解參數名稱和方法參數名稱相同

? ? 捕捉異常處理:可以使用@around? ?獲取??ptpJoinPoint.proceed(); 捕捉異常處理在返回給前端;

package com.BaDun.test.aop;import java.lang.reflect.Method; import java.util.Objects;import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component;import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.BaDun.test.annotation.Loggable; import com.BaDun.test.common.AppResult;/*** Aop接收打印日志.* <p>主要用來截取controller的日志處理和異常捕獲</p>* @author jhon07* @version 1.11* */ @Aspect @Component("loggerAspect") public class LoggerAspect {private Logger logger=LoggerFactory.getLogger(LoggerAspect.class);@Pointcut("@annotation(com.BaDun.test.annotation.Loggable)")public void log(){};/*** * @param joinPoint* @param retVal* @return JSONObject* @author qienay* @since 1.11* */@AfterReturning(value="log()",returning="retVal")public JSONObject log(JoinPoint joinPoint,JSONObject retVal){//獲取參數值Object[] args = joinPoint.getArgs();//獲取方法名稱String methodName=joinPoint.getSignature().getName();//獲取相應的類Class<?> targetClass=joinPoint.getTarget().getClass();Method method=null;for(Method mt:targetClass.getMethods()){if(methodName.equals(mt.getName())){method=mt;break;}}Loggable loggable = method.getAnnotation(Loggable.class);if(Objects.isNull(loggable)){return retVal ;}logger.info("loggable desc:{} ,opType:{},module:{}",loggable.describe(),loggable.optType(),loggable.module(),args);return retVal;};/*** 方法處理后異常打印.* @deprecated* @param joinPoint* @param ex* @return void*/@AfterThrowing(value="log()",throwing="ex")public void log(JoinPoint joinPoint,Exception ex){//獲取參數值Object[] args = joinPoint.getArgs();//獲取方法名稱String methodName = joinPoint.getSignature().getName();//獲取相應類Class<?> targetClass = joinPoint.getTarget().getClass();Method method=null;for(Method mt:targetClass.getMethods()){if(methodName.equals(mt.getName())){method=mt;break;}}Loggable loggable = method.getAnnotation(Loggable.class);if(Objects.isNull(loggable)){return ;}logger.info("loggable desc:{},opType:{},module:[],exception:{},params{}",loggable.describe(),loggable.optType(),loggable.module(),ex.getMessage(),args);}/*** 環繞通知主要用來處理Controller層 異常.* <p>controller 層類{@link com.BaDun.test.controller.testController}<p>* @param joinPoint* @return JSONObject* @author jhon07* @since 1.11*/@Around(value="log()") public JSONObject authorSessionAfter(ProceedingJoinPoint ptpJoinPoint){JSONObject messageJson=null;String methodName=null;Loggable loggable=null;try {//Object proceed = joinPoint.proceed();//獲取方法名methodName= ptpJoinPoint.getSignature().getName();//獲取類型名稱Class<?> targetClass = ptpJoinPoint.getTarget().getClass();Method method=null;for(Method mt:targetClass.getMethods()){if(methodName.equals(mt.getName())){method=mt;break;}}loggable = method.getAnnotation(Loggable.class);//獲取controller傳遞的值Object proceed = ptpJoinPoint.proceed();messageJson=JSON.parseObject(proceed.toString());} catch (Throwable e) {// TODO Auto-generated catch blockString message=methodName+" "+loggable.module()+"異常!";logger.info(message);messageJson=AppResult.getFaileMsg(message);e.printStackTrace();}return messageJson;}}

注意:controller 層? 方法為public 不管是CGlib 還是JDK 創建代理類,首先得能訪問這個類.方法;

@Loggable(describe="查詢Jhon07信息", module = "查詢", optType = "POST")@RequestMapping(value = { "/queryUserInfo" }, method = { RequestMethod.POST }, produces={"application/json;charset=UTF-8"})@ResponseBodypublic void queryUserInfo(....){}

2.使用注解方式實現:

首先是在appliction.xml spring 容器中加入:aop配置

需要注意的是:mehod 不能像注解一樣,使用重載方式,這里的method 的名字都不同的

<!-- AOP配置 --><aop:config><aop:aspect id="controllerAspect" ref="loggerAspects"><aop:pointcut expression="execution(* com.buDun.test.controller.*.*(..))" id="controllPoincut" /><aop:around pointcut-ref="controllPoincut" method="aroundLog" /><aop:after-returning pointcut-ref="controllPoincut" method="afterReturningLog" returning="retVal" /><!-- <aop:after-throwing pointcut-ref="controllPoincut" method="AfterThrowingLog" throwing="ex"/> --></aop:aspect></aop:config>

定義切面類:

package com.buDun.test.aop;import java.lang.reflect.Method; import java.util.Objects;import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component;import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.buDun.test.annotation.Loggable; import com.buDun.test.common.AppResult;/*** Aop接收打印日志.* <p>主要用來截取controller的日志處理和異常捕獲</p>* @author jhon07* @version 1.11* */ @Component("loggerAspects") public class LoggerAspects {private Logger logger=LoggerFactory.getLogger(LoggerAspect.class);public void log(){};/*** * @param joinPoint* @param retVal* @return JSONObject* @author qienay* @since 1.11* */public JSONObject afterReturningLog(JoinPoint joinPoint,JSONObject retVal){//獲取參數值Object[] args = joinPoint.getArgs();//獲取方法名稱String methodName=joinPoint.getSignature().getName();//獲取相應的類Class<?> targetClass=joinPoint.getTarget().getClass();Method method=null;for(Method mt:targetClass.getMethods()){if(methodName.equals(mt.getName())){method=mt;break;}}Loggable loggable = method.getAnnotation(Loggable.class);if(Objects.isNull(loggable)){return retVal ;}logger.info("loggable desc:{} ,opType:{},module:{}",loggable.describe(),loggable.optType(),loggable.module(),args);return retVal;};/*** 方法處理后異常打印.* @deprecated* @param joinPoint* @param ex* @return void*/public void AfterThrowingLog(JoinPoint joinPoint,Exception ex){//獲取參數值Object[] args = joinPoint.getArgs();//獲取方法名稱String methodName = joinPoint.getSignature().getName();//獲取相應類Class<?> targetClass = joinPoint.getTarget().getClass();Method method=null;for(Method mt:targetClass.getMethods()){if(methodName.equals(mt.getName())){method=mt;break;}}Loggable loggable = method.getAnnotation(Loggable.class);if(Objects.isNull(loggable)){return ;}logger.info("loggable desc:{},opType:{},module:[],exception:{},params{}",loggable.describe(),loggable.optType(),loggable.module(),ex.getMessage(),args);}/*** 環繞通知主要用來處理Controller層 異常.* <p>controller 層類{@link com.buDun.test.controller.testController}<p>* @param joinPoint* @return JSONObject* @author jhon07* @since 1.11*/public JSONObject aroundLog(ProceedingJoinPoint ptpJoinPoint){JSONObject messageJson=null;String methodName=null;Loggable loggable=null;try {//Object proceed = joinPoint.proceed();//獲取方法名methodName= ptpJoinPoint.getSignature().getName();//獲取類型名稱Class<?> targetClass = ptpJoinPoint.getTarget().getClass();Method method=null;for(Method mt:targetClass.getMethods()){if(methodName.equals(mt.getName())){method=mt;break;}}loggable = method.getAnnotation(Loggable.class);//獲取controller傳遞的值Object proceed = ptpJoinPoint.proceed();messageJson=JSON.parseObject(proceed.toString());} catch (Throwable e) {// TODO Auto-generated catch blockString message=methodName+" "+loggable.module()+"異常!";logger.info(message);messageJson=AppResult.getFaileMsg(message);e.printStackTrace();}return messageJson;}}

參考:https://blog.csdn.net/kawnj/article/details/84639159

? ? ? ? ? ?https://docs.spring.io/spring-framework/docs/5.1.3.RELEASE/spring-framework-reference/core.html#aop-introduction-proxies

總結

以上是生活随笔為你收集整理的SpringAOP xml 方式和注解简单实现日志处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。