How to programmatically get transaction manager in a thread? How to programmatically get transaction manager in a thread? spring spring

How to programmatically get transaction manager in a thread?


You have to inject the transaction manager in the class you want to use it. You can use constructor or property based injection for it or use autowiring.One you get the transaction manger, you can use the programmatic transaction support in Spring to start and commit the transaction. Here is the sample code from Spring reference 2.5:

public class SimpleService implements Service {  // single TransactionTemplate shared amongst all methods in this instance  private final TransactionTemplate transactionTemplate;  // use constructor-injection to supply the PlatformTransactionManager  public SimpleService(PlatformTransactionManager transactionManager) {    Assert.notNull(transactionManager, "The 'transactionManager' argument must not be null.");    this.transactionTemplate = new TransactionTemplate(transactionManager);  }  public Object someServiceMethod() {    return transactionTemplate.execute(new TransactionCallback() {      // the code in this method executes in a transactional context      public Object doInTransaction(TransactionStatus status) {        updateOperation1();        return resultOfUpdateOperation2();      }    });  }}

See the reference for more details.