Search code examples
javaaspectjspring-aop

how to apply spring aop for legacy code by taking pointcut as input from user


I have to apply Spring AOP for legacy code without changing anything in the existing code. There is no bean concept and the objects are created using new keyword, so no scope of using applicationContext.getBean("beanName"). Also the pointcuts will be taken as input from end user and there will be a common aspect class.

For eg.

package package1;

public class Demo1 {

public void method1()
{
    System.out.println("From method1");
}

public void method2()
{
    System.out.println("From method2");
}

}


package package2;

public class Demo2 {

public void method3()
{
    System.out.println("From method3");
}

public void method4()
{
    System.out.println("From method4");
}

}

package aspects;

public class SpringAspect {

public void beforeAdvice(JoinPoint jointPoint)
{
    System.out.println("Before method : "+jointPoint.getSignature());
}

}

Pointcuts taken as input from end user are as follows and their before advisor method is beforeAdvice() from aspects.SpringAspect class : execution(* package1.Demo1.method1(..)) execution(* package2.Demo2.method4(..))

Also if it is not possible using Spring AOP, how can I use AspectJ during runtime for the same.


Solution

  • First of all, your so-called aspect is missing aspect-related annotations such as @Aspect and @Before, without which it is just a POJO class. It will never be executed or even recognised as an aspect.

    Second, Spring AOP is a proxy-based framework which only works in connection with Spring components, not with POJO classes. You need AspectJ in order to solve your problem. (Have you ever read a tutorial or the Spring or AspectJ manual, by the way? I guess you have not.)

    Furthermore, why on earth would you want a user to enter pointcuts during runtime? Should you not know where to apply your aspects a bit earlier? Even if I would show you a solution creating aspects on the fly, they would not be very valuable because even load-time weaving needs to instrument your Java code during class-loading. If the target classes are already loaded, there is no way to apply aspects on them post factum.

    Maybe you should explain what you want to achieve and not ask how to do something technically which does not make sense and will not work, thus not solve your problem anyway.

    If you want a more dynamic way to define your pointcuts other than hard-coding them within your aspects, you can create an abstract base aspect with an abstract pointcut and define the concrete pointcut in an aop.xml file which is used for load-time weaving, as described in the AspectJ documentation.