Spring AOP基於xml的方式實現

文采杰出發表於2024-06-11
  • 建立目標類
    首先,建立一個簡單的服務類,該類包含一些業務方法。
package com.powernode.spring6.service2;

public class MyService {
    public void doSomething() {
        System.out.println("Doing something in MyService...");
    }

    public String doSomethingElse(String input) {
        System.out.println("Doing something else in MyService with input: " + input);
        return "World " + input;
    }
}
  • 建立切面類
package com.powernode.spring6.service2;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class JournalAspect {
    // 前置通知
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("Before method: " + joinPoint.getSignature().getName());
    }

    // 後置通知
    public void afterAdvice(JoinPoint joinPoint) {
        System.out.println("After method: " + joinPoint.getSignature().getName());
    }

    // 環繞通知
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("Entering method: " + proceedingJoinPoint.getSignature().getName());
        Object result = proceedingJoinPoint.proceed(); // 繼續執行目標方法
        System.out.println("Exiting method: " + proceedingJoinPoint.getSignature().getName());
        return result;
    }
}
  • 配置Spring 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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- 定義服務bean -->
    <bean id="myService" class="com.powernode.spring6.service2.MyService"/>

    <!-- 定義切面bean -->
    <bean id="journalAspect" class="com.powernode.spring6.service2.JournalAspect"/>

    <!--啟用AOP配置-->
    <aop:config>
    <!-- 定義一個切點,匹配com.example.myapp.service包下所有類的所有方法 -->
        <aop:pointcut id="serviceMethods" expression="execution(* com.powernode.spring6.service2.*.*(..))"/>

        <!--定義前置/後置/環繞通知-->
        <aop:aspect ref="journalAspect">
            <aop:around method="aroundAdvice" pointcut-ref="serviceMethods"/>
        </aop:aspect>
    </aop:config>
  • 測試:
    @Test
    public void aspectTest(){
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring-aspect.xml");
        MyService myService = classPathXmlApplicationContext.getBean("myService", MyService.class);
//        myService.doSomething();
        String 你好 = myService.doSomethingElse("你好");
        System.out.println(你好);
    }

相關文章