Junior — Middle
Can you explain what a proxy is in the context of Spring Framework?
sobes.tech AI
Answer from AI
In Spring Framework, proxies are objects that wrap the original bean and intercept method calls to add additional logic, such as for aspect-oriented programming (AOP).
Proxies enable features like transactions, logging, and security without modifying the original class code.
Spring automatically creates proxies using either JDK dynamic proxies (if the bean implements an interface) or CGLIB (if no interface is implemented).
Example of proxy usage for transactions:
@Service
public class UserService {
@Transactional
public void createUser() {
// business logic
}
}
Spring creates a proxy for UserService, which starts a transaction when createUser() is called, executes the method, and commits or rolls back based on the outcome.