简体   繁体   中英

Spring @Transactional doesn't work for an annotated method when called from within service class

In below code , when methodInner() is called from within methodOuter , should be under transaction bounds. But it is not. But when methodInner() is called directly from MyController class , it is bound by transaction. Any explanations?

This is controller class.

@Controller
public class MyController {

    @Autowired
    @Qualifier("abcService")
    private MyService serviceObj;

    public void anymethod() {
        // below call cause exception from methodInner as no transaction exists  
        serviceObj.methodOuter(); 
    }

}

This is service class .

@Service("abcService")
public class MyService {

    public void methodOuter() {
        methodInner();
    }

    @Transactional
    public void methodInner() {
    .....
    //does db operation.
    .....
    }
}

Spring uses Java proxies by default to wrap beans and implement annotated behavior. When doing calls within a service you bypass proxy and run method directly, so annotated behavior is not triggered.

Possible solutions:

  1. Move all @Transactional code to separate service and always do calls to transactional methods from outside

  2. Use AspectJ and weaving to trigger annotated behavior even within a service

@Transactional添加到methodOuter()并且它可以正常工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM