9 Essential Spring Design Patterns Every Java Developer Should Master
This article explores nine commonly used Spring design patterns—including Simple Factory, Factory Method, Singleton, Adapter, Wrapper, Proxy, Observer, Strategy, and Template Method—explaining their concepts, showing XML or Java code examples, and illustrating how Spring implements each pattern in real applications.
Design patterns are essential references for developers, and Spring, as a classic Java framework, exemplifies many of them in both architecture and code.
1. Simple Factory Pattern
Also known as the Static Factory Method, this pattern lets a factory class decide which product class to instantiate based on input parameters. In Spring, BeanFactory acts as a simple factory, retrieving beans by a unique identifier.
<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 Pattern
This pattern separates object creation from usage by delegating instantiation to a factory object. In Spring, a bean can be defined with a factory-method attribute to invoke a static method for object creation.
import java.util.Random;
public class StaticFactoryBean {
public static Integer createRandom() {
return new Integer(new Random().nextInt());
}
} <bean id="random" class="example.chapter3.StaticFactoryBean" factory-method="createRandom" scope="prototype"/> public static void main(String[] args) {
// getBean() returns a random number; without factory-method it would return the factory bean itself
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("config.xml"));
System.out.println("我是IT学习者创建的实例:" + factory.getBean("random").toString());
}3. Singleton Pattern
Ensures a class has only one instance and provides a global access point. In Spring, beans are singleton by default, offering a global access point via the BeanFactory, though the framework does not enforce singleton at the constructor level.
4. Adapter Pattern
Spring AOP uses Advice to enhance target classes. The underlying mechanism relies on proxy patterns (JDK dynamic proxies and CGLIB bytecode generation) to create proxy classes that intercept method calls.
public interface AdvisorAdapter {
boolean supportsAdvice(Advice advice);
MethodInterceptor getInterceptor(Advisor advisor);
}
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) Pattern
Used when a project needs to switch among multiple data sources dynamically. By configuring several DataSource beans in the Spring context and adjusting the sessionFactory 's dataSource property per request, the application can delegate data source selection without changing core business code.
6. Proxy Pattern
Provides a surrogate to control access to another object. In Spring, proxy implementations such as JdkDynamicAopProxy and Cglib2AopProxy realize this pattern within the AOP framework.
7. Observer Pattern
Defines a one‑to‑many dependency so that when one object changes state, all its dependents are notified. Spring applies this pattern in its event system, e.g., ApplicationListener implementations.
8. Strategy Pattern
Encapsulates a family of algorithms, making them interchangeable. Spring uses this pattern during bean instantiation; for example, SimpleInstantiationStrategy selects a concrete strategy at runtime.
9. Template Method Pattern
Defines the skeleton of an algorithm while allowing subclasses to override specific steps. Spring’s JdbcTemplate demonstrates a variant: instead of subclassing, developers pass a callback object that contains the variable logic.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
