Sasa
Sasa

Reputation: 1757

Call different proxyied method from Spring Aspect

I have two different aspects. How do I ensure that when calling method from one aspect, it will still go through proxy chain?

Here is relevant code:

Inner aspect:

@Around("withinReplicatedRepository() && entityMethod() && insertMethod()")
public Object trackInsert(ProceedingJoinPoint jp) throws Throwable {
    return trackChange(jp, ChangeType.INSERT, jp.getArgs()[0]);
}

Outer aspect:

@Around("withinReplicatedRepository() && entityMethod() && autoSaveRepository() && saveMethod()")
public Object saveEntity(ProceedingJoinPoint jp) throws Throwable {
    TransactionUtil.ensureTransactional();

    Object entity = jp.getArgs()[0];
    AutoSaveRepository repository = (AutoSaveRepository)jp.getTarget();
    if (repository.exists(entity)) {
        repository.update(entity);
    } else {
        repository.insert(entity);
    }
    return null;
}

Usage:

AutoSaveRepository<MyEntity> repo = ...;
repo.save(entity);

My problem is that jp.getTarget() will return original class, thus repository.insert() will not be captured by trackInsert.

Upvotes: 1

Views: 1075

Answers (1)

kriegaex
kriegaex

Reputation: 67437

You can try

AopContext.currentProxy()

See Javadoc.

The prerequisite is that you activate proxy exposure, though:

  • In XML you can do this since Spring 3.0.3 via
    <aop:aspectj-autoproxy expose-proxy="true"/>.
  • In annotation-style config your can do it since 4.3.1 via
    @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true),
    see Javadoc

Upvotes: 4

Related Questions