首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring AOP 實戰:日志切面分離業務邏輯完整教程

     編輯:Java 綜合教學

Spring AOP 實戰:日志切面分離業務邏輯完整教程

在項目開發中,方法日志記錄是高頻需求。傳統做法在業務代碼中硬編碼輸出語句,導致代碼耦合、難以維護。本文通過完整示例演示如何使用 Spring AOP 實現日志與業務邏輯的徹底分離。

核心組件設計

1. 目標業務類

package com.importnew;
public class Common {
    public void execute(String username, String password) {
        System.out.println("------------------執行 execute() 方法----------------");
    }
}

2. 切面類

package com.importnew;
import org.aspectj.lang.JoinPoint;

public class Check {
    public void checkValidity() {
        System.out.println("------------------驗證合法性----------------");
    }
    
    public void addLog(JoinPoint j) {
        System.out.println("------------------添加日志----------------");
        Object[] obj = j.getArgs();
        for (Object o : obj) {
            System.out.println(o);
        }
        System.out.println("========checkSecurity==" + j.getSignature().getName());
    }
}

XML 配置 AOP

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="https://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <bean id="common" class="com.importnew.Common"/>
    <bean id="check" class="com.importnew.Check"/>
    
    <aop:config>
        <aop:aspect id="myAop" ref="check">
            <aop:pointcut id="target" expression="execution(* com.importnew.Common.execute(..))"/>
            <aop:before method="checkValidity" pointcut-ref="target"/>
            <aop:after method="addLog" pointcut-ref="target"/>
        </aop:aspect>
    </aop:config>
</beans>

切點表達式詳解

execution(方法修飾符 返回值類型 全限定類名.方法名(參數))

  • execution(public void *(..)):攔截所有 public void 方法
  • execution(* com.importnew.Common.execute(..)):精確匹配 execute 方法
  • execution(* com.importnew..*.*(..)):匹配包及子包所有類的所有方法

測試驗證

package test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.importnew.Common;

public class Client {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        Common c = ctx.getBean("common", Common.class);
        c.execute("user123", "pass456");
        ctx.close();
    }
}

依賴與輸出

必需 JAR 包:spring-aop.jar、aspectjrt.jar、aspectjweaver.jar

執行結果:

------------------驗證合法性----------------
------------------執行 execute() 方法----------------
------------------添加日志----------------
user123
pass456
========checkSecurity==execute

通過 AOP 實現了橫切關注點與業務邏輯的解耦,代碼更清晰、可維護性更強。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved