Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to weave an aspect to dynamically instantiated class?

I use Spring and have an aspect that wraps around some class:

@Aspect
public class LoggingAspect{

    @Around("execution(public * com.service.MyService.doStuff(..))")
    public Object log(){
        ...
    }
}

and in context xml:

<aop:aspectj-autoproxy/>
<bean id="loggingAspect" class="com.bla.bla.bla.LoggingAspect"/>

The problem is that instances of MyService are created at runtime so Spring knows nothing about this class during context initialization phase. Is it possible to use aspects in this case to wrap method calls of a class instantiated using new (not Spring)?

like image 748
Vladimir Avatar asked Feb 01 '26 02:02

Vladimir


1 Answers

If my reading of the Spring docs is correct, you do it like this (for Spring proxy-based weaving):

ProxyFactory factory = new ProxyFactory(new SimplePojo());
factory.addInterface(Pojo.class);
factory.addAdvice(new RetryAdvice());

Pojo pojo = (Pojo) factory.getProxy();

or like this (for AspectJ-style weaving):

AspectJProxyFactory factory = new AspectJProxyFactory(new SimplePojo()); 
factory.addAspect(new RetryAspect());

Pojo proxy = factory.getProxy();

(I drive all my AOP weaving through my bean configuration so I've not needed to use this sort of thing in practice.)

like image 139
Donal Fellows Avatar answered Feb 03 '26 10:02

Donal Fellows