Search code examples
springaopaspectjspring-annotations

Aspectj Spring pointcut on interface doesn't work


Configuring an aspect in Spring as:

@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement
public class TestConfiguration {

    @Bean
    public TransactionAspect transactionAspect(){
        return new TransactionAspect();
    }

And TransactionAspectis:

@Aspect
class TransactionAspect extends TransactionSynchronizationAdapter
{
private final Logger logger = LoggerFactory.getLogger(TransactionAspect.class);

@Before("@annotation(org.springframework.transaction.annotation.Transactional)")
public void registerTransactionSyncrhonization()
{
    TransactionSynchronizationManager.registerSynchronization(this);
}

@Override
public void afterCommit()
{
    logger.info("After commit!");
}

}

If I annotate an implementation method with @Transactional, TransactionAspect is working as expected. But if the annotation is on interface it doesn't work. Is it the normal behavior or I'm doing something wrong?


Solution

  • Annotations on methods are not inherited by subclasses or implementing classes in Java. This might explain why it does not work. Your expectation might have been that your implementing method inherits the annotation from its interface, but this is not true.

    Update: Because I have answered this question several times before, I have just documented the problem and also a workaround in Emulate annotation inheritance for interfaces and methods with AspectJ.