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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/423344.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

call stack and stack buffer overflow

http://en.wikipedia.org/wiki/Call_stack http://en.wikipedia.org/wiki/Stack_buffer_overflow Stack_buffer_overflow里提到的frame pointer 的位置不一样&#xff0c;不同的系统实现应该是不一样的。 运行时的栈是从高地址向低地址分配的&#xff0c;堆是从低地址向高地址…

谈一下我对如何设计微服务接口的理解和思考

微服务是一个独立运行、自带数据存储管理&#xff0c;对外提供接口的自治系统。微服务设计很关键的一点是微服务接口的设计。不同微服务经常是分配给不同的团队开发的&#xff0c;接口是各团队编程的契约。 下面只讨论微服务间接口的设计&#xff0c;至于微服务内部子模块间接…

【C++深度剖析教程7】C++之类中的函数重载

函数重载的回顾&#xff08;接上一篇文章&#xff09;&#xff1a; 函数重载的本质为相互独立的不同的函数C中通过函数名和函数参数确定函数调用无法直接通过函数名得到重载函数的入口地址函数重载必然发生在同一个作用域中 类中的成员函数可以进行重载 构造函数的重载普通成…

Linux 服务器远程控制三剑客Telnet、SSH 和 VNC 之 VNC

使用VNC服务实现远程控制Telnet和SSH服务只能实现基于字符界面的远程控制&#xff0c;如果要基于图形界面进行远程控制&#xff0c;可以借助免费的VNC来完成。VNC是VirtualNetworkComput-ing英文的缩写&#xff0c;它是一款优秀远程控制软件&#xff0c;类似Windows的终端服务。…

嵌入式Linux操作系统移植IMX6开发板之实现USB 自动挂载

学习交流加 个人qq&#xff1a; 1126137994个人微信&#xff1a; liu1126137994学习交流资源分享qq群&#xff1a; 962535112 本篇文章讲述如何实现USB自动挂载&#xff0c;U盘即插即用&#xff0c;不用手动挂载的方法&#xff0c;以及给出U盘自动挂载的原理。 目前做的IMX6开发…

C# 繁体,简体 互转

usingMicrosoft.VisualBasic; publicstaticstringTraditional2Simplified(stringstr) { //繁体转简体 return(Microsoft.VisualBasic.Strings.StrConv(str, Microsoft.VisualBasic.VbStrConv.SimplifiedChinese, 0)); } publicstaticstringSimplified…

【C++深度剖析教程8】C++的操作符重载的概念

之前学习了类的函数重载的概念&#xff0c;今天学习操作符重载的概念。在这之前我们先看一个例子&#xff1a; 上面是一个复数的加法&#xff0c;a为复数的实部&#xff0c;b为复数的虚部&#xff0c;在main函数里我想实现复数c1与c2的加法。很显然&#xff0c;正常的号操作符…

大数据开发者应该知道的分布式系统 CAP 理论

无论你是一个系统架构师&#xff0c;还是一个普通开发&#xff0c;当你开发或者设计一个分布式系统的时候&#xff0c;CAP理论是无论如何也绕不过去的。本文就来介绍一下到底什么是CAP理论&#xff0c;如何证明CAP理论&#xff0c;以及CAP的权衡问题。 CAP理论概述 CAP理论&a…

【C++深度剖析教程11】C++学习之编写代码实现复数类

今天&#xff0c;我来学习将复数的加减乘除以及比较运算&#xff0c;编写一个复数类&#xff0c;方便计算复数之间的运算。具体用的方法就是之前写过的操作符重载的概念来实现&#xff08;操作符重载的概念学习&#xff09;。 那么为了显得清晰&#xff0c;今天写的程序运用模块…

IT餐馆—第二十五回 结对

周五开会时&#xff0c;有人提出在团队中采用结对开发的Agile实践。 当然团队里有人说&#xff0c;如果让新手与水平高的人结对&#xff0c;基本上就是知识的单向传递了&#xff0c;对于新手来说的确是个不错的学习机会&#xff0c;但对于水平高的开发者&#xff0c;就未必不乐…

Spring Cloud各组件总结归纳

前面介绍了很多Spring Cloud的组件&#xff0c;本篇按照自己的角度来做一次归纳。 Spring Cloud技术应用从场景上可以分为两大类&#xff1a;润物无声类和独挑大梁类。 润物无声&#xff0c;融合在每个微服务中、依赖其它组件并为其提供服务。 Ribbon&#xff0c;客户端负载均…

移植Linux系统到iMX6开发板之LVDS显示屏驱动程序的框架分析与移植

学习交流加 个人qq&#xff1a; 1126137994个人微信&#xff1a; liu1126137994学习交流资源分享qq群&#xff1a; 962535112 今天记录一下项目中的关于LVDS显示屏的驱动程序的分析与移植。因为驱动源码厂家已经提供好&#xff0c;我们需要做的就是读懂驱动程序的代码&#xff…

Java api 1.8 中文 帮助文档

java 1.6 帮助文档 中文 链接&#xff1a;http://download.csdn.net/detail/qw599186875/9608735 英文 Java1.8 帮助文档 英文 中文 – 谷歌版 在线版: https://blog.fondme.cn/apidoc/jdk-1.8-google/下载链接&#xff1a;http://download.csdn.net/detail/qw599186875/980219…

设计模式记--Observer Pattern观察者模式

观察者模式——定义了对象之间的一对多依赖&#xff0c;这样一来&#xff0c;当一个对像改变状态时&#xff0c;它的所有依赖者都会收到通知并自动更新. 从定义可以看出,OBSERVER(观察者)模式逻辑上需要两组对象来实现.首先它必需要有发布者(Publish),也可称为被观察的目标 (…

前端学习(64):css继承属性小结

今天来总结一点关于css中哪些属性可以被继承&#xff0c;哪些不可以被继承。不是很全&#xff0c;仅供大家参考&#xff0c;也方便于自己以后复习。 一、不能被继承的属性 1、display&#xff1a;规定元素应该生成的框的类型 2、文本属性&#xff1a; vertical-align、 text…

iMX6开发板移植Linux系统之LVDS显示屏驱动程序分析之LVDS参数的匹配过程分析

学习交流加 个人qq&#xff1a; 1126137994个人微信&#xff1a; liu1126137994学习交流资源分享qq群&#xff1a; 962535112 上一篇分析LVDS驱动程序移植过程的文章&#xff08;文章链接为&#xff1a;移植Linux系统到iMX6开发板之LVDS显示屏驱动程序的框架分析与移植&#xf…

日常spoken英语学习

今天遇到一个老外&#xff0c;说&#xff1a;can you speak engilsh dou you know coffee in here 我是想了半天&#xff0c;第一有点蒙&#xff0c;第二确实忘了&#xff0c;咖啡馆在哪了&#xff0c;回了一句&#xff1a;Iam think 感觉不知道如何组织语言了&#xff0c;口…

【C++深度剖析教程9】初探C++标准库

在这之前&#xff0c;我写的C程序不能叫做标准的C程序&#xff0c;因为里面写的大多数还带有C语言的影子。今天我们来学习C标准库。 首先看一下例子&#xff1a;操作符<<的原生意义是按位左移。那么我们重载这个操作符&#xff0c;将变量或者常量&#xff0c;左移到一个…

Quartus II常见问题集锦

1、 【问题】Pin Planner 的使用问题&#xff1a;在QuartusII 7.2 &#xff0c;时序仿真都通过&#xff0c;但是&#xff0c;一旦使用Pin Planner设定引脚后&#xff0c;时序仿真就发生变化&#xff0c;与功能仿真结果不一致&#xff0c;不是理想的结果。使用Pin Planner时要注…

员工考核UI网页界面(PS大屏文件资料)

现分享人员管理可视化数据统计网页UI、员工考核数据可视化UI网页界面模版的UI源文件&#xff0c;供UI设计师们快速获取PSD源文件完成工作。 若需更多 大屏组件&#xff0c;请移步小7的另一篇文章&#xff1a;数据可视化大屏组件&#xff0c;大屏PSD设计源文件(大屏UI设计规范)…