AOP

Spring AOP AspectJ Example

This is a tutorial of a Spring AOP AspectJ Example. We will explain how to use AspectJ style support in order to integrate Aspect-Oriented Programming in the Spring framework and we will give a spring aop example.

AOP in Spring is used in the Spring Framework to provide declarative enterprise services, especially as a replacement for EJB declarative services. It is also used to allow users to implement custom aspects, complementing their use of OOP with AOP. Spring supports the @AspectJ annotation style approach and the XML-based approach to implement custom aspects. @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations, whereas in the XML-based approach aspects are implemented using regular classes along with XML based configuration. We shall show you how to implement all types of aspects using both approaches.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of the Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using Spring version 3.2.3 and the JDK 7_u_21.

Let’s begin!

 

1.What is Spring AOP? 

Object-Oriented programming compliments Aspect-Oriented programming in spring since it provides modularity. Aspect is the base unit of modularity in AOP. In Object-Oriented Programming, the base unit is an Aspect. Spring Framework has a feature related to Aspect-Oriented Programming. In AOP, the software program is divided into concerns. Cross-cutting concerns are aspects. Aspects span different points in an application. Examples of aspects are security, auditing, logging, caching, declarative transactions, and monitoring. Aspects are similar to triggers in Perl, Java, C#, and .NET. Spring AOP has application interceptors. A good example is an interceptor of method execution. When the method is executed, the interceptor has code to be executed. Custom aspects can be created by developers.

2. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

Spring AOP - New-Maven-Project
New-Maven-Project

In the “Select project name and location” page of the wizard, make sure that the “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.

Spring AOP - Maven-Project-Name-Location
Maven-Project-Name-Location

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample". Hit “Finish” to exit the wizard and to create your project.

Spring AOP - Configure-Maven-Project
Configure-Maven-Project

The Maven project structure is shown below:

Maven-project-structure
project structure
  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

3. Add Spring 3.2.3 dependency

  • Locate the “Properties” section at the “Overview” page of the POM editor and perform the following changes:
    Create a new property with name org.springframework.version and value 3.2.3.RELEASE.
  • Navigate to the “Dependencies” page of the POM editor and create the following dependencies (you should fill the “GroupId”, “Artifact Id” and “Version” fields of the “Dependency Details” section on that page):
    Group Id : org.springframework Artifact Id : spring-web Version : ${org.springframework.version}

Alternatively, you can add the Spring dependencies in Maven’s pom.xml file, by directly editing it at the “Pom.xml” page of the POM editor, as shown below:
 
pom.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javacodegeeks.snippets.enterprise</groupId>
    <artifactId>springexample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
 
    <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>
    </dependencies>
 
    <properties>
        <spring.version>3.2.3.RELEASE</spring.version>
    </properties>
</project>

As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.

4. Add AOP AspectJ dependencies

Add the Spring AOP AspectJ dependencies in Maven’s pom.xml file, in order to enable AspectJ, as shown below:

pom.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javacodegeeks.snippets.enterprise</groupId>
    <artifactId>springexample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
 
    <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>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.4</version>
        </dependency>
 
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.5.4</version>
        </dependency>
 
    </dependencies>
 
    <properties>
        <spring.version>3.2.3.RELEASE</spring.version>
    </properties>
</project>

5.What is advice, joinpoint or pointcut?

Advice is related to actions taken by an aspect at a specific join point. A join point is a place in a program like field access, exception management, and method invocation. Spring has features related to method execution join point. A pointcut is associated with advice. It is invoked at every joinpoint associated with the pointcut.

5.1 Advice

Advice is an action related to an aspect at a specific joinpoint. There are multiple types of advice as mentioned below:

5.11 Types of Advice

  • Before Advice: This gets invoked before a join point.
  • After Returning Advice: This is invoked after a joint point completes normally.
  • After Throwing Advice: This is invoked if the method exits by throwing an exception.
  • After Advice: This gets invoked after a join point regardless of join point exit whether normally or exceptional return.
  • Around Advice: This is invoked before and after a join point.

6. AspectJ using annotations

In order to begin with the annotation-based approach of AspectJ, we first create a simple bean, simpleServiceBean. Specifically, we create an interface, SimpleService.java and its implementation, SimpleServiceImpl.java. The simpleServiceBean consists of a few methods that will be intercepted by AspectJ.

SimpleService.java

01
02
03
04
05
06
07
08
09
10
11
package com.javacodegeeks.snippets.enterprise;
 
public interface SimpleService {
     
    public void printNameId();
 
    public void checkName();
 
    public String sayHello(String message);
 
}

SimpleServiceImpl.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.javacodegeeks.snippets.enterprise.impl;
 
import com.javacodegeeks.snippets.enterprise.SimpleService;
 
public class SimpleServiceImpl implements SimpleService {
 
    private String name;
 
    private int id;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public void printNameId() {
        System.out.println("SimpleService : Method printNameId() : My name is " + name
             + " and my id is " + id);
    }
 
    public void checkName() {
        if (name.length() < 20) {
            throw new IllegalArgumentException();
        }
    }
 
    public String sayHello(String message){
        System.out.println("SimpleService : Method sayHello() : Hello! " + message);
        return message;
    }
}

Now, in order to continue, we will create all kinds of aspects, using the annotations provided by AspectJ to intercept the bean’s methods. Aspects (classes annotated with @Aspect) may have methods and fields just like any other class. They may also contain pointcuts, advice, and introduction (inter-type) declarations. In order to define that a class is an aspect, we must annotate it with the @Aspect annotation. The annotations provided by AspectJ to define what kind of advice the aspect should have are:

  1. @Before
  2. @After
  3. @AfterReturning
  4. @AfterThrowing
  5. @Around

6.1 @Before

The @Before annotation is used to define a Before advice in an aspect. The Before advice is the action taken before reaching a specified join point. The join point is a point during the execution of a program, such as the execution of a method or the handling of an exception. The pointcut expression associated with the Advice must match the joining point so that the advice action is taken. The pointcut expression may be either a simple reference to a named pointcut or a pointcut expression declared in place. The class below is an aspect that has a Before advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..) method will be intercepted:

DoBeforeAspect.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
package com.javacodegeeks.snippets.enterprise.aspect;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
 
@Aspect
public class DoBeforeAspect {
 
    @Before("execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))")
    public void doBefore(JoinPoint joinPoint) {
 
        System.out.println("***AspectJ*** DoBefore() is running!! intercepted : " + joinPoint.getSignature().getName());
    }
 
}

The definition of the aspect’s bean must be included in applicationContext.xml file, along with the simpleServiceBean definition. Note that in order to enable @AspectJ support we must use the aop:aspectj-autoproxy element.

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
 
    <aop:aspectj-autoproxy />
     
    <bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
  
    <bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
  
</beans>

Now, we load the simpleServiceBean in App.java class and invoke its methods.

App.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.javacodegeeks.snippets.enterprise;
 
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class App {
 
    public static void main(String[] args) {
     
            ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            SimpleService simpleService = (SimpleService) context.getBean("simpleServiceBean");
            simpleService.printNameId();
            System.out.println("---------------");
            try{
                simpleService.checkName();
            } catch(Exception e){
                System.out.println("SimpleService checkName() : Exception thrown..");
            }
            System.out.println("---------------");
            simpleService.sayHello("Javacodegeeks");
            System.out.println("---------------");
            context.close();
    }
}

After running the App.java class we see that the sayHello() method of simpleServiceBean is intercepted by the DoBeforeAspect.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
SimpleService : Method sayHello() : Hello! Javacodegeeks
---------------

6.2 @After

The @After annotation is used to define an After advice in an aspect. The After advice is the action taken after reaching a specified join point. For example, if the joining point represents a method execution, the After advice will be executed after the method returns either normally or exceptionally. The class below is an aspect that has an After advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..) method will be intercepted again:

DoAfterAspect.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
package com.javacodegeeks.snippets.enterprise.aspect;
 
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.After;
      
    @Aspect
    public class DoAfterAspect {
      
        @After("execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))")
        public void doAfter(JoinPoint joinPoint) {
      
            System.out.println("***AspectJ*** DoAfter() is running!! intercepted : " + joinPoint.getSignature().getName());
      
        }
      
    }

The new bean is also defined in applicationContext.xml.

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
 
    <aop:aspectj-autoproxy />
     
    <bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
  
    <bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
     
    <bean id="doAfterAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
  
</beans>

After running the App.class again, we can see that the sayHello() method is now intercepted by both aspects:

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

6.3 @AfterReturning

The @AfterReturning annotation is used to define an AfterReturning advice in an aspect. The AfterReturning advice is the action taken after reaching a specified join point. For example, if the joining point represents a method execution, the AfterReturning advice will be executed after the method returns either normally. The class below is an aspect that has an AfterReturning advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..) method will be intercepted again:

DoAfterReturningAspect.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
package com.javacodegeeks.snippets.enterprise.aspect;
 
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.AfterReturning;
      
    @Aspect
    public class DoAfterReturningAspect {
      
       @AfterReturning(
          pointcut = "execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))", returning= "result")
       public void doAfterReturning(JoinPoint joinPoint, Object result) {
      
        System.out.println("***AspectJ*** DoAfterReturning() is running!! intercepted : " + joinPoint.getSignature().getName());
        System.out.println("Method returned value is : " + result);
      
       }
      
    }

Again, the new bean is defined in applicationContext.xml.

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
 
    <aop:aspectj-autoproxy />
     
    <bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
  
    <bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
     
    <bean id="doAfterAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
     
    <bean id="doAfterReturningAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />
  
</beans>

Now, after running the example again, we can see that the sayHello() method is intercepted by the new AfterReturning aspect too since it returns normally.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAfterReturning() is running!! intercepted : sayHello
Method returned value is : Javacodegeeks
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

6.4 @AfterThrowing

The @AfterThrowing annotation is used to define an AfterThrowing advice in an aspect. The AfterThrowing advice is the action taken after reaching a specified join point. For example, if the join point represents a method execution, the AfterThrowing advice will be executed after the method throws an exception. The class below is an aspect that has an AfterThrowing advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.checkName() method will be intercepted. This method throws an exception:

DoAfterThrowingAspect.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
package com.javacodegeeks.snippets.enterprise.aspect;
 
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.AfterThrowing;
      
    @Aspect
    public class DoAfterThrowingAspect {
      
       @AfterThrowing(
          pointcut = "execution(* com.javacodegeeks.snippets.enterprise.SimpleService.checkName(..))",
          throwing= "error")
        public void doAfterThrowing(JoinPoint joinPoint, Throwable error) {
      
        System.out.println("***AspectJ*** DoAfterThrowing() is running!! intercepted : " + joinPoint.getSignature().getName());
        System.out.println("Exception : " + error);
        System.out.println("******");
      
        }
    }

The new bean is defined in applicationContext.xml.

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
    <aop:aspectj-autoproxy />
     
    <bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
  
    <bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
     
    <bean id="doAfterAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
     
    <bean id="doAfterReturningAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />
  
    <bean id="doAfterThrowingAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterThrowingAspect" />
     
</beans>

Now, after running App.java class again, we see that the new aspect intercepts the checkName() method.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
***AspectJ*** DoAfterThrowing() is running!! intercepted : checkName
Exception : java.lang.IllegalArgumentException
******
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAfterReturning() is running!! intercepted : sayHello
Method returned value is : Javacodegeeks
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

6.5 @Around

The @AfterThrowing annotation is used to define an AfterThrowing advice in an aspect. The AfterThrowing advice is the action taken after reaching a specified join point. For example, if the join point represents a method execution, the AfterThrowing advice will be executed after the method throws an exception. The class below is an aspect that has an AfterThrowing advice.

The @Around annotation is used to define an Around advice in an aspect. The Around advice is the action that can actually surround a specified join point, for example it can be executed before or after a method invocation. The class below is an aspect that has an Around advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.sayHello() method will be intercepted. This method throws an exception:

DoAroundAspect.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.javacodegeeks.snippets.enterprise.aspect;
 
import java.util.Arrays;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
 
@Aspect
public class DoAroundAspect {
 
    @Around("execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))")
    public void doAround(ProceedingJoinPoint joinPoint) throws Throwable {
 
        System.out.println("***AspectJ*** DoAround() is running!! intercepted : " +  joinPoint.getSignature().getName()
        + " \narguments : " + Arrays.toString(joinPoint.getArgs()));
 
        System.out.println("***AspectJ*** DoAround() before is running!");
        joinPoint.proceed(); // continue on the intercepted method
        System.out.println("***AspectJ*** DoAround() after is running!");
 
    }
 
}

The new bean is defined in applicationContext.xml file:

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
    <aop:aspectj-autoproxy />
     
    <bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
  
    <bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
     
    <bean id="doAfterAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
     
    <bean id="doAfterReturningAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />
  
    <bean id="doAfterThrowingAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterThrowingAspect" />
     
    <bean id="doAroundAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAroundAspect" />
     
</beans>

Now, after running the application again we can see that the sayHello() method is also intercepted by the around advice.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
***AspectJ*** DoAfterThrowing() is running!! intercepted : checkName
Exception : java.lang.IllegalArgumentException
******
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
***AspectJ*** DoAround() is running!! intercepted : sayHello 
arguments : [Javacodegeeks]
***AspectJ*** DoAround() before is running!
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAround() after is running!
***AspectJ*** DoAfterReturning() is running!! intercepted : sayHello
Method returned value is : null
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

7. AspectJ using xml-configuration

Now, we shall see how all the above steps can be implemented without using annotations in a spring aop example. The XML-based approach of using AspectJ also provides all types of devices. Each aspect, in this case, is simply a regular Java object defined as bean in applicationContext.xml. The state and behavior of the aspect is captured in the fields and methods of the object, and the pointcut and advice information is captured in the applicationContext.xml. An aspect is declared using the <aop:aspect> element, and the backing bean is referenced using the ref attribute. A named pointcut is declared using the <aop:pointcut> element inside the <aop:aspect> element. It holds two attributes, the id, whose value is a given name of the pointcut and the expression, whose value is the pointcut expression. Both aspects and pointcuts are declared inside the <aop:config> element.

7.1 <aop:before>

The <aop:before> element is used inside the <aop:aspect> element to declare a Before aspect. It has two attributes, the method whose value is the name of the advice method, and the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
    <bean id="simpleServiceBean"
        class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
 
    <bean id="doBeforeAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
 
        <aop:aspect id="aspects" ref="doBeforeAspect">
 
            <aop:pointcut id="pointCutBefore"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
 
            <aop:before method="doBefore" pointcut-ref="pointCutBefore" />
 
        </aop:aspect>
 
    </aop:config>
 
</beans>

7.2 <aop:after>

The <aop:after> element is used inside the <aop:aspect> element to declare an After aspect. It also has two attributes, the method whose value is the name of the advice method, and the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
    <bean id="simpleServiceBean"
        class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
 
    <bean id="doBeforeAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
 
    <bean id="doAfterAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
 
    <aop:config>
        <aop:aspect id="aspects" ref="doBeforeAspect">
            <aop:pointcut id="pointCutBefore"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:before method="doBefore" pointcut-ref="pointCutBefore" />
        </aop:aspect>
 
        <aop:aspect id="aspects" ref="doAfterAspect">
            <aop:pointcut id="pointCutAfter"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:after method="doAfter" pointcut-ref="pointCutAfter" />
        </aop:aspect>
 
    </aop:config>
 
</beans>

7.3 <aop:after-returning>

The <aop:after-returning> element is used inside the <aop:aspect> element to declare an AfterReturning aspect. It has three attributes. The first attribute is the method, whose value is the name of the advice method. The second attribute is the returning, whose value is the name of the method parameter to which the return value must be passed. The third attribute is the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 
    <bean id="simpleServiceBean"
        class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
 
    <bean id="doBeforeAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
 
    <bean id="doAfterAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
 
    <bean id="doAfterReturningAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />
 
    <aop:config>
        <aop:aspect id="aspects" ref="doBeforeAspect">
            <aop:pointcut id="pointCutBefore"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:before method="doBefore" pointcut-ref="pointCutBefore" />
        </aop:aspect>
 
        <aop:aspect id="aspects" ref="doAfterAspect">
            <aop:pointcut id="pointCutAfter"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:after method="doAfter" pointcut-ref="pointCutAfter" />
        </aop:aspect>
 
        <aop:aspect id="aspects" ref="doAfterReturningAspect">
            <aop:pointcut id="pointCutAfterReturning"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:after-returning method="doAfterReturning" returning="result" pointcut-ref="pointCutAfterReturning" />
        </aop:aspect>
 
    </aop:config>
 
</beans>

7.4 <aop:after-throwing>

The <aop:after-throwing> element is used inside the <aop:aspect> element to declare an AfterThrowing aspect. It also has three attributes. The first attribute is the method, whose value is the name of the advice method. The second attribute is the throwing, whose value is the name of the method parameter to which the thrown exception must be passed. The third attribute is the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 
    <bean id="simpleServiceBean"
        class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
 
    <bean id="doBeforeAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
 
    <bean id="doAfterAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
 
    <bean id="doAfterReturningAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />
 
    <bean id="doAfterThrowingAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterThrowingAspect" />
 
    <aop:config>
 
        <aop:aspect id="aspects" ref="doBeforeAspect">
            <aop:pointcut id="pointCutBefore"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:before method="doBefore" pointcut-ref="pointCutBefore" />
        </aop:aspect>
         
        <aop:aspect id="aspects" ref="doAfterAspect">
            <aop:pointcut id="pointCutAfter"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:after method="doAfter" pointcut-ref="pointCutAfter" />
        </aop:aspect>
         
        <aop:aspect id="aspects" ref="doAfterReturningAspect">
            <aop:pointcut id="pointCutAfterReturning"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:after-returning method="doAfterReturning" returning="result" pointcut-ref="pointCutAfterReturning" />
        </aop:aspect>
         
        <aop:aspect id="aspects" ref="doAfterThrowingAspect" >
    <aop:pointcut id="pointCutAfterThrowing"
      expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.checkName(..))" />
    <aop:after-throwing method="doAfterThrowing" throwing="error"
      pointcut-ref="pointCutAfterThrowing"  />
  </aop:aspect>
 
    </aop:config>
 
</beans>

7.5 <aop:around>

The <aop:around> element is used inside the <aop:aspect> element to declare an Around aspect. It has two attributes, the method whose value is the name of the advice method, and the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
 
    <bean id="simpleServiceBean"
        class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
        <property name="name" value="Hello" />
        <property name="id" value="12345" />
    </bean>
 
    <bean id="doBeforeAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
 
    <bean id="doAfterAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
 
    <bean id="doAfterReturningAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />
 
    <bean id="doAfterThrowingAspect"
        class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterThrowingAspect" />
 
    <bean id="doAroundAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAroundAspect" />
 
    <aop:config>
 
        <aop:aspect id="aspects" ref="doBeforeAspect">
            <aop:pointcut id="pointCutBefore"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:before method="doBefore" pointcut-ref="pointCutBefore" />
        </aop:aspect>
 
        <aop:aspect id="aspects" ref="doAfterAspect">
            <aop:pointcut id="pointCutAfter"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:after method="doAfter" pointcut-ref="pointCutAfter" />
        </aop:aspect>
 
        <aop:aspect id="aspects" ref="doAfterReturningAspect">
            <aop:pointcut id="pointCutAfterReturning"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:after-returning method="doAfterReturning"
                returning="result" pointcut-ref="pointCutAfterReturning" />
        </aop:aspect>
 
        <aop:aspect id="aspects" ref="doAfterThrowingAspect">
            <aop:pointcut id="pointCutAfterThrowing"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.checkName(..))" />
            <aop:after-throwing method="doAfterThrowing"
                throwing="error" pointcut-ref="pointCutAfterThrowing" />
        </aop:aspect>
 
        <aop:aspect id="aspects" ref="doAroundAspect">
            <aop:pointcut id="pointCutAround"
                expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
            <aop:around method="doAround" pointcut-ref="pointCutAround" />
        </aop:aspect>
 
 
    </aop:config>
 
</beans>

Now. let’s run the application again. The result is the same as the one in the annotations-based case.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
***AspectJ*** DoAfterThrowing() is running!! intercepted : checkName
Exception : java.lang.IllegalArgumentException
******
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
***AspectJ*** DoAround() is running!! intercepted : sayHello 
arguments : [Javacodegeeks]
***AspectJ*** DoAround() before is running!
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAround() after is running!
***AspectJ*** DoAfterReturning() is running!! intercepted : sayHello
Method returned value is : null
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

8. Download the source code

This was an example of AOP AspectJ in Spring.

Download
You can download the full source code of this example here: Spring AOP AspectJ Example

Last updated on Oct. 21st, 2020

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button