AOP based @ AspectJ in Spring

AOP based @ AspectJ in Spring

@AspectJ, as a common Java class annotated by Java 5 annotations, refers to a style of declaring aspects. @ AspectJ support is available by including the following elements in your schema based XML configuration file.

<aop:aspectj-autoproxy/>

You also need to use the following AspectJ library files in your application's CLASSPATH. These library files are available in the 'lib' directory of an AspectJ device. If not, you can download them on the Internet.

  • aspectjrt.jar

  • aspectjweaver.jar

  • aspectj.jar

  • aopalliance.jar

Declare an aspect

Like any other normal bean, except that they will be annotated with @ AspectJ, the Aspects class may have methods and fields like other classes, as shown below:

package org.xyz;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class AspectModule {
}

They will be configured in XML as follows, just like any other bean:

<bean id="myAspect" class="org.xyz.AspectModule">
   <!-- configure properties of aspect here as normal -->
</bean>

Declare a pointcut

A pointcut helps identify the join points (i.e., methods) of interest that are executed using different recommendations. When dealing with configuration based XML schemas, the declaration of the pointcut has two parts:

  • A pointcut expression determines which method we are interested in will actually be executed.

  • A pointcut label contains a name and any number of parameters. The real content of the method is irrelevant, and in fact it should be empty.

In the following example, a pointcut named 'businessService' is defined, which will work with com xyz. myapp. Match each method available in the class under the service package:

import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression 
private void businessService() {}  // signature

In the following example, a pointcut named 'getname' is defined, which will be associated with com The getName() method in the Student class under the tutorial point package matches:

import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.tutorialspoint.Student.getName(..))") 
private void getname() {}

Statement recommendations

You can declare any of the five suggestions using the @{ADVICE-NAME} annotation, as shown below. This assumes that you have defined a pointcut tag method businessService():

@Before("businessService()")
public void doBeforeTask(){
 ...
}
@After("businessService()")
public void doAfterTask(){
 ...
}
@AfterReturning(pointcut = "businessService()", returning="retVal")
public void doAfterReturnningTask(Object retVal){
  // you can intercept retVal here.
  ...
}
@AfterThrowing(pointcut = "businessService()", throwing="ex")
public void doAfterThrowingTask(Exception ex){
  // you can intercept thrown exception here.
  ...
}
@Around("businessService()")
public void doAroundTask(){
 ...
}

You can define your pointcut inline for any suggestion. The following is an example of defining inline pointcuts before recommendations:

@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
 ...
}

AOP based @ AspectJ example

In order to understand the concept of AOP based @ AspectJ mentioned above, let's write an example to implement several suggestions. In order to use a few suggestions in our example, let's make the Eclipse IDE work, and then create a Spring application as follows:

stepdescribe
1 Create a project named "SpringExample", and create a project named "SpringExample. Com" under the "src" folder of the created project A package of tutorialspoint.
2 Use the Add External JARs option to add the required Spring library files, as explained in the Spring Hello World Example Chapter.
3 Add the library file specified by Spring AOP to the project, @ aspectjrt jar, aspectjweaver.jar and AspectJ jar.
4 On , com Create Java classes , Logging, Student , and , MainApp , under the , tutorialpoint , package.
5 Create the Beans configuration file under the {src} folder} Beans xml.
6 The final step is to create the contents of all Java files and Bean configuration files and run the application as explained below.

This is {logging The contents of the Java} file. This is actually an example of an aspect module that defines the methods to be called at various points.

package com.tutorialspoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
@Aspect
public class Logging {
   /** Following is the definition for a pointcut to select
    *  all the methods available. So advice will be called
    *  for all the methods.
    */
   @Pointcut("execution(* com.tutorialspoint.*.*(..))")
   private void selectAll(){}
   /** 
    * This is the method which I would like to execute
    * before a selected method execution.
    */
   @Before("selectAll()")
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
   /** 
    * This is the method which I would like to execute
    * after a selected method execution.
    */
   @After("selectAll()")
   public void afterAdvice(){
      System.out.println("Student profile has been setup.");
   }
   /** 
    * This is the method which I would like to execute
    * when any method returns.
    */
   @AfterReturning(pointcut = "selectAll()", returning="retVal")
   public void afterReturningAdvice(Object retVal){
      System.out.println("Returning:" + retVal.toString() );
   }
   /**
    * This is the method which I would like to execute
    * if there is an exception raised by any method.
    */
   @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
   public void AfterThrowingAdvice(IllegalArgumentException ex){
      System.out.println("There has been an exception: " + ex.toString());   
   }  
}

The following is # student Contents of Java} file:

package com.tutorialspoint;
public class Student {
   private Integer age;
   private String name;
   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }
   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

Here is mainapp Contents of Java} file:

package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");
      Student student = (Student) context.getBean("student");
      student.getName();
      student.getAge();     
      student.printThrowException();
   }
}

The following is the configuration file: beans 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-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

    <aop:aspectj-autoproxy/>

   <!-- Definition for student bean -->
   <bean id="student" class="com.tutorialspoint.Student">
      <property name="name"  value="Zara" />
      <property name="age"  value="11"/>      
   </bean>

   <!-- Definition for logging aspect -->
   <bean id="logging" class="com.tutorialspoint.Logging"/> 

</beans>

Once you have created the source file and bean configuration file, let's run the application. If your application is all right, this will output the following message:

Going to setup student profile.
Name : Zara
Student profile has been setup.
Returning:Zara
Going to setup student profile.
Age : 11
Student profile has been setup.
Returning:11
Going to setup student profile.
Exception raised
Student profile has been setup.
There has been an exception: java.lang.IllegalArgumentException
.....
other exception content

 

Added by thallium6 on Wed, 05 Jan 2022 14:37:03 +0200