How does the @Transactional annotation work in Spring? What is a proxy and when is it created?
sobes.tech AI
Answer from AI
The @Transactional annotation in Spring is used for managing transactions at the method or class level. When a method with this annotation is called, Spring automatically starts a transaction, and after the method execution, it commits or rolls back the transaction depending on the outcome.
Spring implements @Transactional through proxies — these are wrapper objects around your bean that intercept method calls. The proxy is created during the Spring context initialization for beans marked as transactional. It adds logic to start and end the transaction around the method call.
Proxies are created:
- When the Spring context is loaded, if transaction support is enabled.
- For beans whose methods are annotated with
@Transactional.
Example:
@Service
public class UserService {
@Transactional
public void createUser(User user) {
// database operations
}
}
When createUser is called through the proxy, Spring opens a transaction, executes the method, and then closes the transaction, either committing or rolling back.