Spring AOP + AspectJ-Anmerkungsbeispiel

In diesem Lernprogramm zeigen wir Ihnen, wie Sie die AspectJ-Anmerkung in das Spring AOP-Framework integrieren. Mit Spring AOP AspectJ können Sie die Methode einfach abfangen.

Häufige Anmerkungen zu AspectJ:

  1. @ Before - Vor der Methodenausführung ausführen

  2. @ After - Ausführen, nachdem die Methode ein Ergebnis zurückgegeben hat

  3. @ AfterReturning - Ausführen, nachdem die Methode ein Ergebnis zurückgegeben hat

auch das zurückgegebene Ergebnis.

  1. @ AfterThrowing - Ausführen, nachdem die Methode eine Ausnahme ausgelöst hat

  2. @ Around - Durchlaufen Sie die Methodenausführung und kombinieren Sie alle drei Hinweise

über.

1. Verzeichnisstruktur

Siehe Verzeichnisstruktur dieses Beispiels.

Verzeichnisstruktur dieses Beispiels

2. Projektabhängigkeiten

Zum Aktivieren von AspectJ benötigen Sie aspectjrt.jar , aspectjweaver.jar und spring-aop.jar . Siehe folgende Maven-Datei pom.xml .

  • AspectJ wird seit Spring 2.0 unterstützt. ** In diesem Beispiel wird Spring 3 verwendet. Die AspectJ-Funktionen werden jedoch seit Spring 2.0 unterstützt.

Datei: pom.xml

<project ...>

    <properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring AOP + AspectJ -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.11</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.11</version>
        </dependency>

    </dependencies>
</project>

3. Frühlingsbohnen

Normales Bean, mit wenigen Methoden, fängt es später über die AspectJ-Annotation ab.

package com.mkyong.customer.bo;

public interface CustomerBo {

    void addCustomer();

    String addCustomerReturnValue();

    void addCustomerThrowException() throws Exception;

    void addCustomerAround(String name);
}
package com.mkyong.customer.bo.impl;

import com.mkyong.customer.bo.CustomerBo;

public class CustomerBoImpl implements CustomerBo {

    public void addCustomer(){
        System.out.println("addCustomer() is running ");
    }

    public String addCustomerReturnValue(){
        System.out.println("addCustomerReturnValue() is running ");
        return "abc";
    }

    public void addCustomerThrowException() throws Exception {
        System.out.println("addCustomerThrowException() is running ");
        throw new Exception("Generic Error");
    }

    public void addCustomerAround(String name){
        System.out.println("addCustomerAround() is running, args : " + name);
    }
}

4. AspectJ aktivieren

Fügen Sie in der Spring-Konfigurationsdatei „` <aop: aspectj-autoproxy/> `“ ein und definieren Sie Ihren Aspect (Interceptor) und Ihre normale Bean.

Datei: Spring-Customer.xml

<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-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

    <aop:aspectj-autoproxy/>

    <bean id="customerBo" class="com.mkyong.customer.bo.impl.CustomerBoImpl"/>

    <!-- Aspect -->
    <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect"/>

</beans>

4. AspectJ @Before

Im folgenden Beispiel wird die Methode 'logBefore ()' vor der Ausführung der Schnittstelle 'customerCo' (Methode addCustomer ()) ausgeführt.

Datei: LoggingAspect.java

package com.mkyong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {

    @Before("execution(**  com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
    public void logBefore(JoinPoint joinPoint) {

        System.out.println("logBefore() is running!");
        System.out.println("hijacked : " + joinPoint.getSignature().getName());
        System.out.println("** ** ** ** ** ** ");
    }

}

Starte es

    CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
    customer.addCustomer();

Ausgabe

logBefore() is running!
hijacked : addCustomer
** ** ** ** ** **

addCustomer () läuft

5. AspectJ @After

Im folgenden Beispiel wird die Methode `logAfter () 'nach der ausgeführt Ausführung der customerBo-Schnittstelle, Methode 'addCustomer ()'.

Datei: LoggingAspect.java

Paket com.mkyong.aspect;

import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.After;

@Aspect öffentliche Klasse LoggingAspect {

@After ("Ausführung (**  com.mkyong.customer.bo.CustomerBo.addCustomer (..))") public void logAfter (JoinPoint joinPoint) {

System.out.println ("logAfter () läuft!"); System.out.println ("hijacked:" + joinPoint.getSignature (). GetName ()); System.out.println ("** ** ** ** ** ** ");

}

}

Starte es

CustomerBo customer = (CustomerBo) appContext.getBean ("customerBo");
    customer.addCustomer ();

Ausgabe

addCustomer () läuft logAfter () läuft!

entführt: addCustomer
** ** ** ** ** **

6. AspectJ @AfterReturning

In dem folgenden Beispiel wird die Methode 'logAfterReturning ()' nach der Ausführung der Methode 'addCustomerReturnValue ()' der customerBo-Schnittstelle ausgeführt. Außerdem können Sie den zurückgegebenen Wert mit dem Attribut „ returning “ abfangen.

Um den zurückgegebenen Wert abzufangen, muss der Wert des "returning" -Attributs (Ergebnis) mit dem Methodenparameter (Ergebnis) identisch sein.

Datei: LoggingAspect.java

package com.mkyong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;

@Aspect
public class LoggingAspect {

   @AfterReturning(
      pointcut = "execution(**  com.mkyong.customer.bo.CustomerBo.addCustomerReturnValue(..))",
      returning= "result")
   public void logAfterReturning(JoinPoint joinPoint, Object result) {

    System.out.println("logAfterReturning() is running!");
    System.out.println("hijacked : " + joinPoint.getSignature().getName());
    System.out.println("Method returned value is : " + result);
    System.out.println("** ** ** ** ** ** ");

   }

}

Starte es

    CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
    customer.addCustomerReturnValue();

Ausgabe

addCustomerReturnValue() is running
logAfterReturning() is running!
hijacked : addCustomerReturnValue
Method returned value is : abc
** ** ** ** ** **

7. AspectJ @AfterReturning

In below example, the logAfterThrowing() method will be executed if the customerBo interface, addCustomerThrowException() method is throwing an exception.

File : LoggingAspect.java

Paket com.mkyong.aspect;

import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.AfterThrowing;

@Aspect öffentliche Klasse LoggingAspect {

@AfterThrowing (pointcut = "Ausführung (**  com.mkyong.customer.bo.CustomerBo.addCustomerThrowException (..))", warf = "error")

System.out.println ("logAfterThrowing () läuft!"); System.out.println ("hijacked:" joinPoint.getSignature (). GetName ()); System.out.println (Fehler "Ausnahme:"); System.out.println ("** ** ** ** ** ** ");

}
}

Starte es

CustomerBo customer = (CustomerBo) appContext.getBean ("customerBo");
    customer.addCustomerThrowException ();

Ausgabe

addCustomerThrowException () läuft logAfterThrowing () läuft!

entführt: addCustomerThrowException
Ausnahme: java.lang.Exception: Generischer Fehler
** ** ** ** ** **
Ausnahme im Thread "main" java.lang.Exception: Generic Error
   //...

8. AspectJ @Around

In dem folgenden Beispiel wird die Methode 'logAround ()' vor der customerBo-Schnittstelle, der Methode 'addCustomerAround ()' ausgeführt, und Sie müssen die Definition von 'joinPoint.proceed (); `definieren, um zu steuern, wann der Interceptor das zurückgeben soll steuern Sie die ursprüngliche Methode 'addCustomerAround ()'.

Datei: LoggingAspect.java

package com.mkyong.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;

@Aspect
public class LoggingAspect {

   @Around("execution(**  com.mkyong.customer.bo.CustomerBo.addCustomerAround(..))")
   public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {

    System.out.println("logAround() is running!");
    System.out.println("hijacked method : " + joinPoint.getSignature().getName());
    System.out.println("hijacked arguments : " + Arrays.toString(joinPoint.getArgs()));

    System.out.println("Around before is running!");
    joinPoint.proceed();//continue on the intercepted method
    System.out.println("Around after is running!");

    System.out.println("** ** ** ** ** ** ");

   }

}

Starte es

    CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
    customer.addCustomerAround("mkyong");

Ausgabe

logAround() is running!
hijacked method : addCustomerAround
hijacked arguments :[mkyong]Around before is running!
addCustomerAround() is running, args : mkyong
Around after is running!
** ** ** ** ** **

Conclusion

It’s always recommended to apply the least power AsjectJ annotation. It’s rather long article about AspectJ in Spring. for further explanations and examples, please visit the reference links below.

Download Source Code

Download it – Spring3-AOP-AspectJ-Example.zip (8 KB)