Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

AOP-based @AspectJ


May 14, 2021 Spring


Table of contents


AOP-based @AspectJ

@AspectJ as a normal Java class annotated with Java 5 comments, it refers to a style that declares aspects. By including the following elements in your schema-based XML profile, @AspectJ support is available.

<aop:aspectj-autoproxy/>

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

  • aspectjrt.jar

  • aspectjweaver.jar

  • aspectj.jar

  • aopalliance.jar

Declare a aspect

Aspects classes, like any other normal bean, may have methods and fields like other classes, in addition to the @AspectJ comments they will use, as follows:

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>

Declares an entry point

An entry point helps you identify points of interest (that is, methods) that are performed with different recommendations. When working with configuration-based XML architectures, there are two parts to the declaration of entry points:

  • An entry point expression determines which method we are interested in will actually be executed.

  • An entry point label contains a name and any number of parameters. The true content of the method is irrelevant, and it should actually be empty.

The following example defines an entry point called 'businessService' that matches each method available in the class under the com.xyz.myapp.service package:

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

The following example defines an entry point called 'getname' that matches the getName() method in the Student class under the com.tutorialspoint package:

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

Declare recommendations

You can declare any of the five recommendations using the comments for the hashtags . Let's say you've defined an entry-point labeling 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 entry point inline for any of the recommendations. Here's an example of defining an inline entry point before suggesting it:

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

Examples of AOP@AspectJ examples

To understand the above concept of AOP-@AspectJ, let's write an example that implements several recommendations. To use a few suggestions in our example, let's put the Eclipse IDE to work, and then follow these steps to create a Spring application:

Steps Describe
1 Create a project called SpringExample, and create a package called com.tutorialspoint under the src folder of the project you created.
2 Use the Add External JARs option to add the required Spring library files, as explained in the Spring Hello World Example section.
3 Add Spring AOP-specified library files aspectjrt.jar, aspectjweaver, .jar and aspectj .jar.
4 Create Java-class Logging, Student, and MainApp under the com.tutorialspoint package.
5 Create the Beans profile Beans file under the src .xml.
6 The final step is to create the contents of all Java files and bean profiles and run the application as explained below.

Here is the .java Logging file. This is actually an example of a aspect module that defines methods 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());   
   }  
}

Here's .java student 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's what .java mainApp files are:

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();
   }
}

Here's the profile .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've finished creating the source file and bean profile, 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