简体   繁体   中英

Java: calling public transactional method from a private method

I have two classes

public class MyTest {
    @Autowired
    private MyService myService;

    private void test() {
        myService.writeToDb();
    }
}

@Service
public class MyService {
    @Transactional
    public void writeToDb() {
        // do db related stuff
    }
}

I want to know if calling a method test() (which is a private method) from MyTest class would create a transaction.

PS

I'm using Spring Boot. And Java 17.

It will work, whether you call the method of another object from a public or private method inside yours is an implementation detail. From callee's point of view, it's the same, it is not even aware of the caller's context.

Spring AOP uses the Proxy pattern to handle those scenarios. It means you are not directly receiving a MyService bean, but a MyServiceSpringCreatedProxy (not the actual name, check in debug mode and you'll see), which is actually handling transactions around methods.

So as long as the call passes through the Spring's proxy, the @Transactional will be accounted for as expected. Bear in mind that it doesn't mean a new transaction is open, it depends if another already exists and your configuration.

However, any self call (to a public or a private method) would not pass through the proxy and then @Transactional would not be working.

@Service
public class MyService {

   // can be private, public or whatever
    public void callRelatedStuff() {
       //self call, no transactional work done
       writeToDb();
    }

    @Transactional
    public void writeToDb() {
        // do db related stuff
    }
}

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