Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing AOP in Spring Framework

Tech 3

To use AOP in Spring, include the AspectJ weaver dependency in your project:

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
</dependencies>

Method 1: Using Spring API Interfaces

Configuration:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="accountService" class="com.example.service.AccountServiceImpl"/>
    <bean id="preLog" class="com.example.log.PreLog"/>
    <bean id="postLog" class="com.example.log.PostLog"/>

    <aop:config>
        <aop:pointcut id="servicePointcut" expression="execution(* com.example.service.AccountServiceImpl.*(..))"/>
        <aop:advisor advice-ref="preLog" pointcut-ref="servicePointcut"/>
        <aop:advisor advice-ref="postLog" pointcut-ref="servicePointcut"/>
    </aop:config>
</beans>

Service Interface:

public interface AccountService {
    void create();
    void remove();
    void modify();
    void retrieve();
}

Service Implementation:

public class AccountServiceImpl implements AccountService {
    @Override
    public void create() {
        System.out.println("Creating an account");
    }

    @Override
    public void modify() {
        System.out.println("Modifying an account");
    }

    @Override
    public void remove() {
        System.out.println("Removing an account");
    }

    @Override
    public void retrieve() {
        System.out.println("Retrieving an account");
    }
}

Advice Classes:

public class PreLog implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + " method " + method.getName() + " is being executed");
    }
}
public class PostLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("Executed " + method.getName() + " method, result: " + returnValue);
    }
}

Test:

public class TestApp {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService service = ctx.getBean("accountService", AccountService.class);
        service.create();
    }
}

Method 2: Custom AOP Implementation

Custom Advice Clas:

public class CustomAdvice {
    public void preAction() {
        System.out.println("--- Before method execution ---");
    }

    public void postAction() {
        System.out.println("--- After method execution ---");
    }
}

Configuration:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="accountService" class="com.example.service.AccountServiceImpl"/>
    <bean id="customAdvice" class="com.example.diy.CustomAdvice"/>

    <aop:config>
        <aop:aspect ref="customAdvice">
            <aop:pointcut id="customPointcut" expression="execution(* com.example.service.AccountServiceImpl.*(..))"/>
            <aop:before method="preAction" pointcut-ref="customPointcut"/>
            <aop:after method="postAction" pointcut-ref="customPointcut"/>
        </aop:aspect>
    </aop:config>
</beans>

Method 3: Annotation-Based AOP

Aspect Class:

@Aspect
public class AnnotationAspect {
    @Before("execution(* com.example.service.AccountServiceImpl.*(..))")
    public void beforeExecution() {
        System.out.println("--- Before method execution ---");
    }

    @After("execution(* com.example.service.AccountServiceImpl.*(..))")
    public void afterExecution() {
        System.out.println("--- After method execution ---");
    }

    @Around("execution(* com.example.service.AccountServiceImpl.*(..))")
    public void aroundExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Around advice before");
        Signature sig = joinPoint.getSignature();
        System.out.println("Signature: " + sig);
        Object result = joinPoint.proceed();
        System.out.println("Around advice after");
        System.out.println("Result: " + result);
    }
}

Configuration:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="accountService" class="com.example.service.AccountServiceImpl"/>
    <bean id="annotationAspect" class="com.example.diy.AnnotationAspect"/>
    <aop:aspectj-autoproxy/>
</beans>

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.