最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用spring aop 統(tǒng)一捕獲異常和寫日志的示例demo

 更新時間:2021年08月26日 11:17:38   作者:noobrookie  
本文通過一個小demo給大家介紹spring AOP 實現(xiàn)的異常捕獲和日志的方法技巧,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧

之前給大家介紹過Spring AOP的基礎(chǔ)知識,需要的朋友點擊了解下吧,這邊我將給您介紹用spring AOP 實現(xiàn)的異常捕獲和日志的小demo,我也會詳細解釋相關(guān)配置。

首先給大家看一下我的工程目錄:

大家可以先用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>/*</url-pattern>
</filter-mapping>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>

//這邊是加載spring的配置文件
<param-value>/WEB-INF/config/spring-mvc-config.xml</param-value>
</init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <session-config> <session-timeout>20</session-timeout> </session-config></web-app>

配置完web.xml后,你可開始配置spring配置文件了,也就是applicationContext.xml文件。如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"
	default-lazy-init="true">
	<description>Spring公共配置</description>

<!-- 使用annotation 自動注冊bean, 并保證@Required、@Autowired的屬性被注入 -->

<context:component-scan base-package="com.zy.test">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />//不掃描controller注解類
    <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />//不掃描ControllerAdvice注解類
</context:component-scan>

</beans>

然后配置spring-mvc-config.xml文件,如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"  
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd ">
	<!-- 自動掃描 -->
	<context:component-scan base-package="com.zy.test" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />//掃描COntroller注解類
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />//掃描ControllerAdvice注解類
	</context:component-scan>
	<mvc:annotation-driven>
		<mvc:message-converters register-defaults="true">
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<constructor-arg value="UTF-8" />
				<property name="writeAcceptCharset" value="false" />
			</bean>
			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="prettyPrint" value="true" />
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	<!--  
	 <bean class="com.zy.test.config.ExceptionConfig"/>
	-->
       <!-- 這里的配置可以通過 com.zy.test.config.ExceptionConfig這個注解類來完成 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />
    <bean class="com.zy.test.aspect.WebExceptionAspect" scope="singleton"/> //配置了單例

</beans>

上面spring容器和spring-mvc容器中掃描的類不一樣,是為了區(qū)分兩個容器的職責,spring-mvc負責controller控制器這塊的類。因為我們的異常捕獲是從controller類往外拋,所以我們對于aspect類也放在spring-mvc容器中。

下面就開始介紹我們的切面類:

package com.zy.test.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.zy.test.annotation.ArchivesLog;

/**

 * web 異常切面

 * @author user
   *
    */
   @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("異常中的參數(shù):");
       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("操作中的參數(shù):");
       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})  //注解可以用于參數(shù)或者方法上
@Retention(RetentionPolicy.RUNTIME)  //保留至運行時
@Documented//被javadoc所記錄
public @interface ArchivesLog {
    /**

   * 操作類型
      @return
          */
         public String operationType() default "";


    /**

   * 操作名稱
      @return
          */
         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 = "測試異?;蛘邷y試返回")
    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實現(xiàn)類:

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上可以拉到新代碼:代碼在這里

到此這篇關(guān)于spring aop 統(tǒng)一捕獲異常和寫日志的文章就介紹到這了,更多相關(guān)spring aop統(tǒng)一異常日志內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springBoot項目中的全局異常處理和自定義異常處理實現(xiàn)

    springBoot項目中的全局異常處理和自定義異常處理實現(xiàn)

    異常是由于程序邏輯錯誤、運行環(huán)境問題、用戶輸入錯誤等原因?qū)е碌囊环N非正常的狀態(tài)或事件,本文主要介紹了springBoot項目中的全局異常處理和自定義異常處理實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2024-08-08
  • velocity顯示List與Map的方法詳細解析

    velocity顯示List與Map的方法詳細解析

    以下是對velocity顯示List與Map的方法進行了詳細的介紹。需要的朋友可以過來參考下
    2013-08-08
  • java中的Reference類型用法說明

    java中的Reference類型用法說明

    這篇文章主要介紹了java中的Reference類型用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • idea切換分支的時候,忽略一些無用的修改設置

    idea切換分支的時候,忽略一些無用的修改設置

    這篇文章主要介紹了idea切換分支的時候,忽略一些無用的修改操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Spring依賴注入底層原理詳解

    Spring依賴注入底層原理詳解

    這篇文章主要介紹了Spring依賴注入底層原理詳解,??依賴注入是一種設計模式,它將對象之間的依賴關(guān)系從代碼中移除,并由容器來管理這些依賴關(guān)系,依賴注入的主要目的是降低代碼的耦合度,使代碼更加靈活和可維護,需要的朋友可以參考下
    2023-09-09
  • 實現(xiàn)一個簡單Dubbo完整過程詳解

    實現(xiàn)一個簡單Dubbo完整過程詳解

    這篇文章主要為大家介紹了實現(xiàn)一個簡單Dubbo完整過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-07-07
  • Elasticsearch?計數(shù)分詞中的token使用實例

    Elasticsearch?計數(shù)分詞中的token使用實例

    這篇文章主要為大家介紹了Elasticsearch?計數(shù)分詞中的token使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-01-01
  • 探討java深拷貝

    探討java深拷貝

    這篇文章主要針對java深拷貝的相關(guān)內(nèi)容進行解析,幫助大家學習理解java深拷貝,感興趣的小伙伴們可以參考一下
    2016-02-02
  • 解決SpringBoot中使用@Transactional注解遇到的問題

    解決SpringBoot中使用@Transactional注解遇到的問題

    這篇文章主要介紹了SpringBoot中使用@Transactional注解遇到的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Spring?Boot中使用@Value加載配置的方法

    Spring?Boot中使用@Value加載配置的方法

    @Value注解相信很多Spring Boot的開發(fā)者都已經(jīng)有接觸了,通過使用該注解,我們可以快速的把配置信息加載到Spring的Bean中,這篇文章主要介紹了為什么不推薦在SpringBoot中使用@Value加載配置,需要的朋友可以參考下
    2024-05-05

最新評論

古蔺县| 庄浪县| 香格里拉县| 裕民县| 宿松县| 邯郸市| 顺昌县| 新余市| 绍兴市| 大安市| 青冈县| 綦江县| 金乡县| 邹城市| 临泉县| 甘泉县| 高密市| 金山区| 桐柏县| 台南县| 福建省| 获嘉县| 六盘水市| 鹿泉市| 和林格尔县| 南部县| 蓬安县| 丘北县| 潞西市| 瓮安县| 巧家县| 和政县| 清涧县| 丰顺县| 清镇市| 额敏县| 呼玛县| 甘德县| 登封市| 宜城市| 柯坪县|