2

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?

Ignasi
  • 5,887
  • 7
  • 45
  • 81

2 Answers2

4

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.

Community
  • 1
  • 1
kriegaex
  • 63,017
  • 15
  • 111
  • 202
  • A related question, I have my service interface annotated with `@Transactional`and all the implementation methods runs with its own transaction. But if annotations are not inherited, how is this posible? – Ignasi Dec 12 '14 at 14:46
  • 1
    I said annotations *on methods* are not inherited. For classes there is an [`@Inherited` meta annotation](http://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Inherited.html) which works for classes, but it is *not* inherited by a class implementing an interface. [`@Transactional` is `@Inherited`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html), but only from superclass to subclass. If it works for you with interfaces, this seems to be a Spring AOP feature. – kriegaex Dec 12 '14 at 15:36
0

To make this work you need to add proxyTargetClass=true in aop config like @EnableAspectJAutoProxy(proxyTargetClass=true) for java based configuration or <aop:config proxy-target-class="true"></aop:config> for xml based configuration. This way spring aop will add the proxies forcefully.