Spring: register advice programmatically at runtime

The previous solution is too invasive as it not only creates advice on the fly but also handles advising beans. This replicates functionality of Spring’s AbstractAdvisorAutoProxyCreator, specifically the getAdvicesAndAdvisorsForBean method, where Spring will locate and apply eligible Advisors to each bean. A better approach is to simply programmatically create Advisors and let Spring handle the rest of the plumbing of advising beans, creating proxies, and so forth.

A simple way of creating a Advisor is to create a Advisor bean using the @Bean annotation:

@Bean
    public Advisor advisorBean() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* com.testit.MyAspectedService.*(..))");
        return new DefaultPointcutAdvisor(pointcut, new MyMethodInterceptor());
    }

Where the class MyMethodInterceptor implements the MethodInterceptor interface:

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;

public class MyMethodInterceptor implements MethodInterceptor {


    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("in interceptor");

        //get the method and arguments we are intercepting
        Method method = invocation.getMethod();
        Object[] arguments = invocation.getArguments();
        //... do stuff before the method
        //call the underlying method
        return invocation.proceed();
    }

}

What this does is to create a around advice Advisor bean named “advisorBean” for all methods calls to a Spring bean MyAspectedService declared as

@Service
public class MyAspectedService {

    //various service methods
}

This approach focuses on only creating the necessary Advisors and interception implementation and delegates the weaving of the aspect to the Spring framework.

Leave a Comment