cyrilantony
cyrilantony

Reputation: 294

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.
    .....
    }
}

Upvotes: 5

Views: 5311

Answers (2)

Leo Huanca
Leo Huanca

Reputation: 1

Add @Transactional to methodOuter() and it works.

Upvotes: 0

hoaz
hoaz

Reputation: 10153

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

Upvotes: 6

Related Questions