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

落花浮王杯 提交于 2019-11-29 04:19:18

It happens because to process both annotations MAGIC is used.

I suppose there are several things happens:

  1. UserServiceImpl is created.
  2. @Scheduled annotation is processed and reference to bean is stored to invoke it at appropriate time.
  3. @Transactional annotation is processed. It create proxy which store reference to original bean. Original bean is replaced to proxy in application context.

If step 2 and 3 passed in different order then you had no problem.

I don't know how to control order in which annotation is processed. I don't even sure it is possible at all.

There is basically two solution.

  1. Use different kind of magic to process @Transaction. Default way is to create proxy object, but it is possible to instruct Spring to instrument current class.
  2. Split this to two class each of them will have method with only one annotation.

Example:

@Service
public class UserServiceImpl implements UserService {

    @Override
    @Transactional
    public void doSomething() {

    }
}

@Service
public class UserServiceScheduler {

    @Inject
    private UserService service;

    @Scheduled(fixedRateString = "${somestring}",initialDelayString = "${anotherstring}")
    public void doSomething() {
         service.doSomething();
    }
}

I'm personally recommend second approach.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!