Junior — Middle
Can you name and explain the types of Proxy used in Spring Framework?
sobes.tech AI
Answer from AI
Spring Framework uses two main types of proxies for aspect-oriented programming (AOP) and other mechanisms:
-
JDK Dynamic Proxy
- Creates proxies based on interfaces.
- Works only with objects that implement at least one interface.
- The proxy implements the same interfaces as the target object.
-
CGLIB Proxy
- Creates proxies by inheriting from the target class.
- Used if the object does not have interfaces or if explicitly configured to use class-based proxies.
- Allows proxying classes without interfaces.
Spring automatically chooses the proxy type: if interfaces are present — JDK Proxy, otherwise CGLIB.
Example configuration:
@Service
public class MyService {
public void doWork() {
// ...
}
}
When using AOP, Spring will create a proxy for MyService, selecting the appropriate type based on the presence of interfaces.