Spring Design Patterns Interview: The One Question That Can Make or Break Your Offer
This article breaks down Spring’s layered architecture and walks through ten core design patterns—factory, singleton, proxy, template method, observer, adapter, decorator, strategy, chain of responsibility, facade, and delegate—showing how they appear in real interview scenarios and how mastering them can turn a tough interview question into a winning advantage.
Spring Architecture Overview
Spring is built on a highly modular architecture where each module can be used independently or combined. The core is the IoC container , which underpins all higher‑level features such as Bean creation, AOP, transaction management, and Web request handling.
Core Container Layer
The core container consists of spring-core, spring-beans, spring-context and spring-expression. These modules provide the fundamental APIs for bean definition, dependency injection, event publishing, resource loading, and expression evaluation.
┌─────────────────────────────────────────────────────────────────┐
│ ApplicationContext (extends BeanFactory) │
└─────────────────────────────────────────────────────────────────┘
▲
│ inherits
┌─────────────────────────────────────────────────────────────────┐
│ BeanFactory (basic container) │
└─────────────────────────────────────────────────────────────────┘Business Layers (AOP, Web, Data, Test)
Four "business" lines extend the core container:
AOP line : provides cross‑cutting concerns via dynamic proxies.
Data line : abstracts JDBC, ORM, and transaction handling.
Web line : handles MVC, WebFlux, WebSocket, and servlet integration.
Test line : supplies testing utilities.
Key Design Patterns Used in Spring
1. Factory Pattern
Spring’s BeanFactory and ApplicationContext are classic factories that encapsulate object creation. The container parses BeanDefinition metadata and instantiates beans via getBean().
// BeanFactory interface
public interface BeanFactory {
Object getBean(String name);
boolean containsBean(String name);
}
// DefaultListableBeanFactory implements the factory logic2. Singleton Pattern
All beans are singleton by default. The SingletonBeanRegistry stores instances in a thread‑safe map, ensuring "lookup → cache hit → create & cache" semantics.
// Simplified singleton cache
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>();
public Object getSingleton(String beanName) {
return singletonObjects.get(beanName);
}3. Proxy (Dynamic Proxy) Pattern
AOP creates proxies using ProxyFactory. For interfaces it uses JDK dynamic proxies ( JdkDynamicAopProxy); otherwise CGLIB ( CglibAopProxy) is employed.
// Proxy creation flow
ProxyFactory factory = new ProxyFactory(target);
Object proxy = factory.getProxy(); // returns JDK or CGLIB proxy4. Template Method Pattern
Classes such as JdbcTemplate and RestTemplate define a fixed algorithm skeleton (resource acquisition, exception handling, cleanup) while delegating variable steps to callbacks.
// JdbcTemplate query example
List<User> users = jdbcTemplate.query(
"SELECT * FROM user WHERE id = ?",
new Object[]{id},
(rs, rowNum) -> new User(rs.getString("name"), rs.getInt("age"))
);5. Observer Pattern
Spring’s event system uses ApplicationEvent, ApplicationListener, and ApplicationEventPublisher to broadcast state changes without tight coupling.
// Publishing an event
applicationEventPublisher.publishEvent(new ContextRefreshedEvent(this));
// Listener implementation
@Component
public class MyListener implements ApplicationListener<ContextRefreshedEvent> {
public void onApplicationEvent(ContextRefreshedEvent e) { /* handle */ }
}6. Adapter Pattern
The HandlerAdapter interface adapts various handler types (annotated methods, legacy Controllers, Servlets) to a uniform handle() contract used by DispatcherServlet.
// Simplified HandlerAdapter
public interface HandlerAdapter {
boolean supports(Object handler);
ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler);
}7. Decorator Pattern
BeanWrapperand its implementation BeanWrapperImpl wrap a bean to add property conversion, type conversion, and validation capabilities.
// BeanWrapper usage
BeanWrapper bw = new BeanWrapperImpl(user);
bw.setPropertyValue("name", "Alice");
Object name = bw.getPropertyValue("name");8. Strategy Pattern
Many Spring extensions are strategy‑based: PlatformTransactionManager (different transaction strategies), HttpMessageConverter (JSON, XML, Protobuf), ResourceLoader, and ViewResolver (JSP, Thymeleaf, FreeMarker).
// Transaction manager selection
PlatformTransactionManager tm = new DataSourceTransactionManager(dataSource);
// or JpaTransactionManager for JPA9. Chain of Responsibility
Handler interceptors form a chain ( HandlerInterceptor) where each can decide to continue or abort request processing.
// Interceptor chain execution
for (HandlerInterceptor i : interceptors) {
if (!i.preHandle(request, response, handler)) return false;
}10. Facade & Delegate Pattern
DispatcherServletacts as a façade that delegates request handling to HandlerMapping, HandlerAdapter, ViewResolver, etc., providing a single entry point for the entire MVC flow.
// Core dispatch flow (simplified)
public void doDispatch(HttpServletRequest request, HttpServletResponse response) {
Object handler = getHandler(request);
HandlerAdapter ha = getHandlerAdapter(handler);
ModelAndView mv = ha.handle(request, response, handler);
render(mv, request, response);
}Design‑Pattern Chain for a REST Call
A typical request follows these steps, each illustrating a pattern:
RestTemplate – Template Method + Strategy (client‑side HTTP).
DispatcherServlet – Facade + Delegate.
HandlerMapping – Strategy to locate the @RequestMapping method.
HandlerAdapter – Adapter to invoke the method.
HttpMessageConverter – Strategy for request/response conversion.
@Transactional – Dynamic Proxy + AOP + Strategy (transaction manager).
JdbcTemplate – Template Method + Callback for DB access.
ViewResolver – Strategy to choose JSP/Thymeleaf/FreeMarker.
Exception handling – Strategy chain + Observer (event publishing).
Conclusion
Spring’s extensive use of classic design patterns—factory, singleton, proxy, template method, observer, adapter, decorator, strategy, chain of responsibility, facade, and delegate—gives the framework its high extensibility and low coupling. Understanding these patterns, the way they are wired together, and the concrete code examples provided equips developers to answer interview questions confidently and demonstrate deep architectural insight.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tech Freedom Circle
Crazy Maker Circle (Tech Freedom Architecture Circle): a community of tech enthusiasts, experts, and high‑performance fans. Many top‑level masters, architects, and hobbyists have achieved tech freedom; another wave of go‑getters are hustling hard toward tech freedom.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
