HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring AOP / Spring AOP Before Advice Example

Spring AOP Before Advice Example

In this spring aop example, we will learn to use AOP before advice using <aop:before/> configuration. Methods configured as before advice, run immediately before the methods which match the pointcut expression passed as argument.

In this example, We will create simple spring application, add logging aspect and then invoke aspect methods based on pointcuts information passed in <aop:before/> xml configuration.

Creating Spring AOP Before Advice

To create a before advice, using xml configuration, use <aop:before/> in below manner.

<aop:config> 
    <aop:aspect ref="loggingAspect">
        <aop:pointcut expression="execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))" id="loggingPointcuts"/>
        <!-- before advice -->
        <aop:before method="logBeforeAllMethods" pointcut-ref="loggingPointcuts" /> 
    </aop:aspect> 
</aop:config>

Project Structure

Spring AOP Project Structure
Spring AOP Project Structure

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 http://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>

Add Spring AOP Configuration

In XML config file, you can add aop:config element to add AOP 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 ">

    <aop:config> 
        <aop:aspect ref="loggingAspect">
            <aop:pointcut expression="execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))" id="loggingPointcuts"/>
            <!-- before advice -->
            <aop:before method="logBeforeAllMethods" pointcut-ref="loggingPointcuts" /> 
        </aop:aspect> 
    </aop:config> 
        
    <!-- Employee manager -->
    <bean id="employeeManager" class="com.howtodoinjava.app.service.impl.EmployeeManagerImpl" />

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

</beans>

Service methods on 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");
    }
}

Write Aspect Class and Methods

Write aspect class and methods to be executed as advice.

package com.howtodoinjava.app.aspect;

import org.aspectj.lang.JoinPoint;

public class LoggingAspect {

    public void logBeforeAllMethods(JoinPoint jp) throws Throwable 
    {
        System.out.println("****LoggingAspect.logBeforeAllMethods() " + jp.getSignature().getName());
    }
}

Test Spring AspectJ Configuration and Execution

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.logBeforeAllMethods() getEmployeeById

Method getEmployeeById() called

****LoggingAspect.logBeforeAllMethods() createEmployee

Method createEmployee() called

Clearly aspect advices executed on relevant jointpoints.

Happy Learning !!

References:

Spring AOP Reference
AspectJ Project
Different Pointcut Expressions With Examples

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Spring AOP Tutorial

  • AOP – Introduction
  • AOP – Annotation Config
  • AOP – XML Config
  • AOP – @Before
  • AOP – @After
  • AOP – @Around
  • AOP – @AfterReturning
  • AOP – @AfterThrowing
  • AOP – Before Advice
  • AOP – After Advice
  • AOP – Around Advice
  • AOP – After-Returning Advice
  • AOP – After-Throwing Advice
  • AOP – Pointcut Expressions
  • AOP – Aspects Ordering
  • AOP – Transactions
  • AOP – Interview Questions

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)