Why @Scheduled annotation doesn't work with @Transaction annotation. Spring Boot

Viewed 8903

I have a question: Why when we annotate method with @Scheduled and @Transaction, transaction doesn't work? I know that the @Scheduled call my class instead of proxy class that created by Spring, but can't understand this behavior.

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Override
    @Scheduled(fixedRateString = "${somestring}",initialDelayString = "${anotherstring}")
    @Transactional
    public void doSomething() {

        }
    }

I have two solutions of this problem:

  1. Call proxy from Scheduled method.

  2. Implement ConcurrentTaskScheduler and replace object of ScheduledMethodRunnable(that is with my class) with object of ScheduledMethodRunnable with proxy.

But this solutions is very inconvenient.

Can you explaim me why @Scheduled works like this?

Thank you!

2 Answers

The Question is not private or public, the question is: How is it invoked and which AOP implementation you use!

If you use (default) Spring Proxy AOP, then all AOP functionality provided by Spring (like @Transational) will only be taken into account if the call goes through the proxy. -- This is normally the case if the annotated method is invoked from another bean.

This has two implications:

  • Because private methods must not be invoked from another bean (the exception is reflection), their @Transactional Annotation is not taken into account.
  • If the method is public, but it is invoked from the same bean, it will not be taken into account either (this statement is only correct if (default) Spring Proxy AOP is used).

you can also use the aspectJ mode, instead of the Spring Proxies, that will overcome the problem. And the AspectJ Transactional Aspects are woven even into private methods (checked for Spring 3.0).

refer: http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/html/aop.html#aop-proxying

Related