Unravelling the magic of @Transacional annotation in Spring

Pradipta Nag
2 min readApr 20, 2024

Whenever there is a requirement to implement transaction management in a Spring application, as a developer, we just add @Transactional annotation and the entire transaction management is taken care of by Spring internally. But as a developer, it is absolutely important to understand how it works internally.

Spring uses the Proxy design pattern internally for managing the transactions.

Consider the following method which has the @Transactional annotation added to it.

@Service
public class EmployeeService {

private final EmployeeDao employeeDao;

public EmployeeService(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}

@Transactional
public Employee createEmployee(Employee employee) {
//Validate the Employee object
validateEmployee(employee);
employeeDao.createEmployee(employee);
}
}

Spring will identify all the classes with @Transactional annotation added to them and create proxy objects for each of them. A proxy class for the above class will look like below.

public class EmployeeServiceProxy {

private final EmployeeService employeeService;

public EmployeeServiceProxy(EmployeeService employeeService) {
this.employeeService = employeeService;
}

public Employee createEmployee(Employee employee) {
try {
System.out.println("Start the transaction here");
Employee employee = employeeService.createEmployee(employee);
System.out.println("Commit the transaction here");
} catch(RuntimeException ex) {
System.out.println("Rollback the transaction here");
throw ex;
} finally {
System.out.println("Close the transaction here");
}
}
}

Instead of the actual object, this proxy object will be injected by the Spring framework wherever the service class has been referenced so that the Transaction handling process is handled by the framework like above.

Spring uses the Cglib library for creating the proxy objects.

A look into the spring-core jar where cglib library is present

To summarise, here are the high-level steps through which the Spring Transaction Handling mechanism works -

  1. Spring framework finds out all the classes with @Transactional annotation added to them.
  2. Spring framework creates the proxy objects for all these classes like above and injects them as and when required.
  3. Whenever the the classes with @Transactional annotation get called, the proxy objects get called which has the Transaction handling code in them which in turn calls the actual object and handles the transaction based on the result from the actual object.

That was a brief explanation of how the @Transactional annotation works in Spring, I hope it will be helpful to all the developers.

--

--

Pradipta Nag

Software Engineer by profession, Singer and Blogger by passion