Spring @Transactional not working for annotated method when called from service class

In the code below, when methodInner () is called from methodOuter, it must be below transaction boundaries. But this is not the case. But when the Inner () method is called directly from the MyController class, it is bound by a transaction. Any explanations?

This is a 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 the class of service .

@Service("abcService")
public class MyService {

    public void methodOuter() {
        methodInner();
    }

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

      

+3


source to share


2 answers


Spring uses a default Java proxy to wrap beans and implement annotated behavior. When making calls inside the service, you just bypass the proxy and run the method, so the annotated behavior is not triggered.

Possible solutions:



  • Move all @Transactional

    code to separate service and always make calls to transactional methods from outside

  • Use AspectJ and weave to trigger annotated behavior even inside a service

+3


source


Add @Transactional

in methodOuter()

and it works.



0


source







All Articles