Spring AOP AspectJ @Around Annotation Example

In this spring aop example, we will learn to use aspectj @Around annotation. @Around annotated methods run before and after the all methods matching with pointcut expression.

In this example, We will create simple spring application, add logging around aspect and then invoke aspect methods based on pointcuts information passed in @Around annotation.

1. AspectJ @Around annotation usage

@Around advice surrounds a joinpoint such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

@Aspect
public class LoggingAspect {

    @Around("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))")
    public void logAroundAllMethods(ProceedingJoinPoint joinPoint) { ... }

    @Around("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.getEmployeeById(..))")
    public void logAroundGetEmployee(ProceedingJoinPoint joinPoint) { ... }
}
Do not forget to use ProceedingJoinPoint as parameter. You must call ProceedingJoinPoint.proceed(); method, else the original method will be executed.

2. Project Structure

Spring AOP Project Structure
Spring AOP Project Structure

3. Spring AOP AspectJ maven dependencies

I have added spring core, spring aop and aspectj dependencies.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd;
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.howtodoinjava</groupId>
    <artifactId>SpringAOPExamples</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring AOP Examples</name>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>
    </dependencies>
</project>

4. Enable Spring AOP AspectJ Support

In XML config file, you can add aop:aspectj-autoproxy element to enable @AspectJ annotation support.

<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 ">

    <!-- Enable @AspectJ annotation support  -->
    <aop:aspectj-autoproxy />
    
    <!-- Employee manager -->
    <bean id="employeeManager" class="com.howtodoinjava.app.service.impl.EmployeeManagerImpl" />

    <!-- Logging Aspect -->
    <bean id="loggingAspect" class="com.howtodoinjava.app.aspect.LoggingAspect" />

</beans>

5. Methods around which aspects needs to be executed

EmployeeManager.java and EmployeeManagerImpl.java

public interface EmployeeManager 
{
    public EmployeeDTO getEmployeeById(Integer employeeId);

    public List<EmployeeDTO> getAllEmployee();

    public void createEmployee(EmployeeDTO employee);

    public void deleteEmployee(Integer employeeId);

    public void updateEmployee(EmployeeDTO employee);
}

public class EmployeeManagerImpl implements EmployeeManager 
{
    public EmployeeDTO getEmployeeById(Integer employeeId) 
    {
        System.out.println("Method getEmployeeById() called");
        return new EmployeeDTO();
    }

    public List<EmployeeDTO> getAllEmployee() 
    {
        System.out.println("Method getAllEmployee() called");
        return new ArrayList<EmployeeDTO>();
    }

    public void createEmployee(EmployeeDTO employee)
    {
        System.out.println("Method createEmployee() called");
    }

    public void deleteEmployee(Integer employeeId) 
    {
        System.out.println("Method deleteEmployee() called");
    }

    public void updateEmployee(EmployeeDTO employee) 
    {
        System.out.println("Method updateEmployee() called");
    }
}

6. Write AspectJ Annotated Class and Methods

Write aspectj annotated class and methods with pointcut information.

@Aspect
public class LoggingAspect {

    @Around("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))")
    public void logAroundAllMethods(ProceedingJoinPoint joinPoint) throws Throwable 
    {
        System.out.println("****LoggingAspect.logAroundAllMethods() : " + joinPoint.getSignature().getName() + ": Before Method Execution");
        try {
            joinPoint.proceed();
        } finally {
            //Do Something useful, If you have
        }
        System.out.println("****LoggingAspect.logAroundAllMethods() : " + joinPoint.getSignature().getName() + ": After Method Execution");
    }

    @Around("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.getEmployeeById(..))") 
    public void logAroundGetEmployee(ProceedingJoinPoint joinPoint) throws Throwable 
    {
        System.out.println("****LoggingAspect.logAroundGetEmployee() : " + joinPoint.getSignature().getName() + ": Before Method Execution");
        try {
            joinPoint.proceed();
        } finally {
            //Do Something useful, If you have
        }
        System.out.println("****LoggingAspect.logAroundGetEmployee() : " + joinPoint.getSignature().getName() + ": After Method Execution");
    }

    @Around("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.createEmployee(..))")
    public void logAroundCreateEmployee(ProceedingJoinPoint joinPoint) throws Throwable 
    {
        System.out.println("****LoggingAspect.logAroundCreateEmployee() : " + joinPoint.getSignature().getName() + ": Before Method Execution");
        try {
            joinPoint.proceed();
        } finally {
            //Do Something useful, If you have
        }
        System.out.println("****LoggingAspect.logAroundCreateEmployee() : " + joinPoint.getSignature().getName() + ": After Method Execution");
    }
}

7. Spring AspectJ @Around example

Now let’s test whether above configured aspects execute on given pointcut information.

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.howtodoinjava.app.model.EmployeeDTO;
import com.howtodoinjava.app.service.EmployeeManager;

public class TestMain 
{
    @SuppressWarnings("resource")
    public static void main(String[] args) {
 
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        EmployeeManager manager = (EmployeeManager) context.getBean("employeeManager");
 
        manager.getEmployeeById(1);
        manager.createEmployee(new EmployeeDTO());
    }
}
****LoggingAspect.logAroundAllMethods() : getEmployeeById: Before Method Execution
****LoggingAspect.logAroundGetEmployee() : getEmployeeById: Before Method Execution

Method getEmployeeById() called

****LoggingAspect.logAroundGetEmployee() : getEmployeeById: After Method Execution
****LoggingAspect.logAroundAllMethods() : getEmployeeById: After Method Execution

****LoggingAspect.logAroundAllMethods() : createEmployee: Before Method Execution
****LoggingAspect.logAroundCreateEmployee() : createEmployee: Before Method Execution

Method createEmployee() called

****LoggingAspect.logAroundCreateEmployee() : createEmployee: After Method Execution
****LoggingAspect.logAroundAllMethods() : createEmployee: After Method Execution

Clearly aspect advices executed around relevant jointpoints.

Happy Learning !!

References:

Spring AOP Reference
@Around Annotation
@Aspect Annotation
AspectJ Annotation Config Example
Different Pointcut Expressions With Examples

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.