Spring’s 9 Core Design Patterns Explained with Code Examples

This article walks through nine common design patterns used in the Spring framework—Simple Factory, Factory Method, Singleton, Adapter, Decorator, Proxy, Observer, Strategy, and Template Method—showing their concepts, Spring-specific implementations, and practical code snippets.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Spring’s 9 Core Design Patterns Explained with Code Examples

Simple Factory Pattern

The Simple Factory (also called Static Factory Method) creates product objects based on a parameter supplied to a factory class. In Spring, BeanFactory acts as a simple factory, returning beans identified by a unique 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>

Factory Method Pattern

To separate object creation from usage, Spring can manage a factory bean whose static method creates the target object. The static method is declared in a regular Java class and referenced via factory-method in the bean definition.

import java.util.Random;
public class StaticFactoryBean {
    public static Integer createRandom() {
        return new Integer(new Random().nextInt());
    }
}

Bean definition using the static factory method:

<bean id="random" class="example.chapter3.StaticFactoryBean" factory-method="createRandom" scope="prototype" />

Test code:

public static void main(String[] args) {
    // Retrieve a random number bean
    XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("config.xml"));
    System.out.println("我是IT学习者创建的实例:" + factory.getBean("random").toString());
}

Singleton Pattern

Spring’s default bean scope is singleton, ensuring a single shared instance per container, which provides a global access point similar to the classic Singleton pattern. The scope can be changed with singleton="true|false" or the scope attribute.

Adapter Pattern

Spring AOP uses the Adapter concept to convert various Advice types into a common interceptor form. The framework supports both JDK dynamic proxies and CGLIB bytecode generation to create proxy objects that apply cross‑cutting concerns.

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);
    }
}

Decorator (Wrapper) Pattern

When an application must switch among multiple data sources at runtime, Spring can configure each DataSource bean and dynamically set the appropriate one on the SessionFactory. Classes whose names contain “Wrapper” or “Decorator” typically implement this dynamic responsibility addition.

Proxy Pattern

Spring’s proxy mechanism controls access to target objects, similar to the Proxy pattern. It is used extensively in AOP, with implementations such as JdkDynamicAopProxy and Cglib2AopProxy.

Observer Pattern

The Observer pattern defines a one‑to‑many dependency so that when a subject changes state, all its observers are notified. In Spring, this appears in event listeners like ApplicationListener.

Strategy Pattern

Spring applies the Strategy pattern when selecting an algorithm at runtime. For example, SimpleInstantiationStrategy chooses different instantiation strategies based on configuration.

Illustration of the strategy usage (image omitted for brevity):

Template Method Pattern

The Template Method defines the skeleton of an algorithm while allowing subclasses to override specific steps. Spring’s JdbcTemplate uses a callback object to inject custom behavior without subclassing, effectively achieving the same goal.

Example: the execute method of JdbcTemplate accepts a callback that contains the variable code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendDesign PatternsJavaspringdependency-injection
Senior Brother's Insights
Written by

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'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.