Sobes.tech
Junior — Middle

How to initiate a new transaction in a service without using internal dependencies (Self Injection)?

sobes.tech AI

Answer from AI

In Spring, to initiate a new transaction without using self-injection, you can apply programmatic transaction management through TransactionTemplate or PlatformTransactionManager.

Example using TransactionTemplate:

@Service
public class MyService {

    private final TransactionTemplate transactionTemplate;

    public MyService(PlatformTransactionManager transactionManager) {
        this.transactionTemplate = new TransactionTemplate(transactionManager);
    }

    public void method() {
        transactionTemplate.execute(status -> {
            // code executed in a new transaction
            return null;
        });
    }
}

This approach allows explicit management of transaction boundaries without the need to call methods through the bean's proxy (self-injection). It is especially useful when you need to ensure that the code runs within a new transaction.