iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >使用spring aop 统一捕获异常和写日志的示例demo
  • 372
分享到

使用spring aop 统一捕获异常和写日志的示例demo

2024-04-02 19:04:59 372人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

之前给大家介绍过spring aop的基础知识,需要的朋友点击了解下吧,这边我将给您介绍用spring AOP 实现的异常捕获和日志的小demo,我也会详细解释相关配置。 首先给大家

之前给大家介绍过spring aop的基础知识,需要的朋友点击了解下吧,这边我将给您介绍用spring AOP 实现的异常捕获和日志的小demo,我也会详细解释相关配置。

首先给大家看一下我的工程目录:

大家可以先用eclipse中新建一个Maven工程,在工程中pom.xml按下面文件添加依赖:


<project xmlns="Http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zy</groupId>
  <artifactId>AOPException</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>AOPException Maven WEBapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
        <groupId>aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.5.2</version>
    </dependency>
        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.0.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>5.0.6.RELEASE</version>
	</dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.13</version>
    </dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-annotations</artifactId>
	    <version>2.9.5</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-core</artifactId>
	    <version>2.9.5</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
	    <version>2.9.5</version>
	</dependency>
	<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastJSON</artifactId>
        <version>1.2.47</version>
    </dependency>
    <dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-test</artifactId>
	    <version>5.0.6.RELEASE</version>
	    <scope>test</scope>
    </dependency>
	<dependency>
	    <groupId>org.mockito</groupId>
	    <artifactId>mockito-core</artifactId>
	    <version>2.18.3</version>
	    <scope>test</scope>
	</dependency>
  </dependencies>
  <build>
    <finalName>AOPException</finalName>
  </build>
</project>

添加完依赖后,开始配置web.xml文件,如下:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    <display-name>exception-test-web</display-name>
     

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>//这边是加载spring的配置文件
        /WEB-INF/config/applicationContext.xml
    </param-value>
</context-param>
<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>production</param-value>
</context-param>
<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>
   @Aspect
   public class WebExceptionAspect {

   @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")//连接点是@RequestMapping注解的方法
   private void webPointcut() {}

   @AfterThrowing(pointcut = "webPointcut()", throwing = "e")//切点在webpointCut()
   public void handleThrowing(JoinPoint joinPoint, Exception e) {//controller类抛出的异常在这边捕获
       String className = joinPoint.getTarget().getClass().getName();
       String methodName = joinPoint.getSignature().getName();
       Object[] args = joinPoint.getArgs();
       //开始打log
       System.out.println("异常:" + e.getMessage());
       System.out.println("异常所在类:" + className);
       System.out.println("异常所在方法:" + methodName);
       System.out.println("异常中的参数:");
       System.out.println(methodName);
       for (int i = 0; i < args.length; i++) {
           System.out.println(args[i].toString());
       }
   }


   @Before("execution(* com.zy.test.controller.*.*(..))")
   public void beforeProcess(JoinPoint joinPoint) {
       String className = joinPoint.getTarget().getClass().getName();
       String methodName = joinPoint.getSignature().getName();
       Object[] args = joinPoint.getArgs();
       //在项目中最好记录当前操作的时间和用户
       System.out.println("操作所在类:" + className);
       System.out.println("操作所在方法:" + methodName);
       System.out.println("操作中的参数:");
       for (int i = 0; i < args.length; i++) {
           System.out.println(args[i].toString());
       }
   }

   @AfterReturning(value = "execution(* com.zy.test.controller.*.*(..)))", returning = "returnVal")
   public void returnProcess(JoinPoint joinPoint, Object returnVal) {
       String className = joinPoint.getTarget().getClass().getName();
       String methodName = joinPoint.getSignature().getName();
       Object[] args = joinPoint.getArgs();
       Class targetClass = null;
       String operationName = "";
       try {
           targetClass = Class.forName(className);
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
       Method[] methods = targetClass.getMethods();
       for (Method method : methods) {
           if (method.getName().equals(methodName)) {
               Class[] clazzs = method.getParameterTypes();
               if (clazzs != null && clazzs.length == args.length&&
                       method.getAnnotation(ArcHivesLog.class)!=null) {//这块是取出我们注解ArchiveLog中的值,一遍在日志时明确这个操作的名称
                   operationName = method.getAnnotation(ArchivesLog.class).operationName();
                   break;
               }
           }
       }
       System.out.println("操作名称:" + operationName);
       System.out.println("方法正常返回的值:" + returnVal);
   }

}

这边我们需要自定义注解:


package com.zy.test.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;

@Target({ElementType.PARAMETER, ElementType.METHOD})  //注解可以用于参数或者方法上
@Retention(RetentionPolicy.RUNTIME)  //保留至运行时
@Documented//被javadoc所记录
public @interface ArchivesLog {
    
         public String operationType() default "";


    
         public String operationName() default "";

}

然后定义我们的controller类:


package com.zy.test.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.zy.test.annotation.ArchivesLog;
import com.zy.test.service.ExceptionService;


@Controller
@RequestMapping("/exception")
public class ExceptionController {
    @Autowired
    private ExceptionService service;
    

    @RequestMapping(value = "/test/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8" )
    @ResponseBody
    @ArchivesLog(operationType = "测试", operationName = "测试异常或者测试返回")
    public JSONObject test(@PathVariable Integer id) throws Exception {
        JSONObject result = new JSONObject();
        result.put("zhouyu", "asdasdasdasd");

//        try {//去掉注释可以测捕获的异常,不去掉注释可以测日志处理
//            service.test();
//        } catch (Exception ex) {
//            throw new Exception("controller 层 异常");
//        }
        return result;
    }
}

service接口:


package com.zy.test.service;

public interface ExceptionServiceBase {
    void test() throws Exception;
}

service实现类:


package com.zy.test.service;

import org.springframework.stereotype.Service;

@Service
public class ExceptionService implements ExceptionServiceBase{
    public void test() throws Exception {
        boolean flag = true;
        if(flag) {
            throw new Exception("service 异常");
        }
    }
}

其中工程中的ExceptionConfig是一个配置类,用于扫描包的。但是如果你是用配置文件的化,这个文件就不用了,这边就不说了。

GitHub上可以拉到新代码:代码在这里

到此这篇关于spring aop 统一捕获异常和写日志的文章就介绍到这了,更多相关spring aop统一异常日志内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 使用spring aop 统一捕获异常和写日志的示例demo

本文链接: https://www.lsjlt.com/news/133652.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作