9 Essential Spring Design Patterns Explained with Code Samples
This article walks through nine commonly used design patterns in Spring, such as Simple Factory, Factory Method, Singleton, Adapter, Wrapper, Proxy, Observer, Strategy, and Template Method, providing clear explanations, XML configurations, and Java code examples to illustrate each pattern in practice.
Design patterns are essential tools for building robust applications, and Spring, as a leading Java framework, implements many of them. This guide presents nine typical patterns used in Spring, explains their purpose, and shows concrete XML and Java code snippets.
1. Simple Factory
The simple factory (static factory method) creates objects based on a parameter. In Spring, BeanFactory acts as a simple factory, retrieving beans by ID. Example XML configuration:
<beans>
<bean id="singletonBean" class="com.itxxz.HelloItxxz">
<constructor-arg><value>Hello! 这是singletonBean!value</value></constructor-arg>
</bean>
<bean id="itxxzBean" class="com.itxxz.HelloItxxz" singleton="false">
<constructor-arg><value>Hello! 这是itxxzBean! value</value></constructor-arg>
</bean>
</beans>2. Factory Method
Factory Method separates object creation from usage. A static method can be exposed to Spring via factory-method attribute. Java class example:
import java.util.Random;
public class StaticFactoryBean {
public static Integer createRandom() {
return new Integer(new Random().nextInt());
}
}Spring XML configuration:
<bean id="random" class="example.chapter3.StaticFactoryBean" factory-method="createRandom" scope="prototype"/>Test code:
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("config.xml"));
System.out.println("Instance: " + factory.getBean("random").toString());
}3. Singleton
Ensures a class has only one instance and provides a global access point. In Spring, beans are singleton by default, but the container does not enforce singleton at the constructor level; it manages any Java object as a bean.
4. Adapter
Spring AOP uses adapters to convert Advice objects into MethodInterceptors. Example interface and implementation:
public interface AdvisorAdapter {
boolean supportsAdvice(Advice advice);
MethodInterceptor getInterceptor(Advisor advisor);
}
public class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
public boolean supportsAdvice(Advice advice) {
return advice instanceof MethodBeforeAdvice;
}
public MethodInterceptor getInterceptor(Advisor advisor) {
MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
return new MethodBeforeAdviceInterceptor(advice);
}
}5. Wrapper (Decorator)
Used when a project must switch among multiple data sources at runtime. All data sources are defined in applicationContext, and the sessionFactory can be reconfigured per request to point to the appropriate source, illustrating the decorator’s dynamic responsibility addition.
6. Proxy
Provides controlled access to another object. Spring’s proxy pattern appears in AOP implementations such as JdkDynamicAopProxy and Cglib2AopProxy, distinguishing it from the decorator which adds responsibilities.
7. Observer
Defines a one‑to‑many dependency so that when an object changes, all dependents are notified. In Spring, the observer pattern is used for event listeners, e.g., ApplicationListener implementations.
8. Strategy
Encapsulates a family of algorithms and makes them interchangeable. Spring applies the strategy pattern in object instantiation; for instance, SimpleInstantiationStrategy selects a concrete creation algorithm. The following diagram shows the strategy in action:
9. Template Method
Defines the skeleton of an algorithm, allowing subclasses to redefine certain steps. Spring’s JdbcTemplate uses this pattern. Instead of subclassing, a callback object can supply the variable part. Example of JdbcTemplate.execute usage is illustrated below:
These nine patterns demonstrate how Spring leverages classic design principles to provide flexible, maintainable, and extensible solutions for common development challenges.
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.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
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.
