Search code examples
javaspringsingletonprototypespring-transactions

Should @transactional services be singleton or prototype in spring?


Will transaction management be a problem in spring if the service layer class is singleton? Or should it be prototype?


Solution

  • No that should not be a problem. What the @Transactional annotation will do is bind the Transaction lifecyle to the current thread. So each new thread will be run in a separate transaction.

    So when your method is invoked, Spring will wrap that method call into a Transaction, so in a single threaded context, a transaction will start and commit if the invocation is successful, and rollback (depending on your config) if an exception is thrown.

    In a multithreaded context, each Thread will run in a separate transaction.