Spring 主要用到的设计模式

Spring 框架使用了多种 设计模式 来实现其核心功能,如 IOC(控制反转)、AOP(面向切面编程)、事务管理、Bean 生命周期管理 等。以下是 Spring 主要用到的设计模式:


1. 创建型模式(Creational Patterns)

(1)工厂模式(Factory Pattern)

Spring 使用 工厂模式 来创建和管理 Bean 对象,避免手动 new 对象,解耦代码。

Spring 相关实现:

  • BeanFactoryApplicationContext 都是 工厂模式 的体现。
  • FactoryBean<T>:自定义 Bean 的创建方式。

示例:

@Component
public class MyBean {
    public void sayHello() {
        System.out.println("Hello from MyBean!");
    }
}
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyBean myBean = context.getBean(MyBean.class);
myBean.sayHello();

这里 ApplicationContext 充当了 工厂,负责创建 MyBean 的实例。


(2)单例模式(Singleton Pattern)

Spring 默认所有 Bean 都是单例,即 Spring 容器内每个 Bean 只会被创建一次,提高性能并减少资源消耗。

Spring 相关实现:

  • DefaultSingletonBeanRegistry 维护了 Spring 容器中的单例对象。

示例:

@Service
public class SingletonService {
    public SingletonService() {
        System.out.println("SingletonService 构造方法调用");
    }
}
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
SingletonService s1 = context.getBean(SingletonService.class);
SingletonService s2 = context.getBean(SingletonService.class);
System.out.println(s1 == s2); // true

📌 注意

  • 如果需要每次获取新实例,可以使用 @Scope("prototype") 改变默认单例模式。

(3)原型模式(Prototype Pattern)

Spring 允许 Bean 以 原型模式 方式创建,每次 getBean() 都会返回一个新的实例。

示例:

@Component
@Scope("prototype")  // 设置为原型模式
public class PrototypeBean {
    public PrototypeBean() {
        System.out.println("PrototypeBean 构造方法调用");
    }
}
PrototypeBean p1 = context.getBean(PrototypeBean.class);
PrototypeBean p2 = context.getBean(PrototypeBean.class);
System.out.println(p1 == p2); // false(每次获取的 Bean 都是新实例)

2. 结构型模式(Structural Patterns)

(4)代理模式(Proxy Pattern)

Spring 的 AOP(面向切面编程) 依赖 代理模式,用于在方法执行前后插入逻辑,如 事务管理、日志记录、权限控制 等。

Spring 相关实现:

  • JDK 动态代理(基于接口)
  • CGLIB 动态代理(基于子类)

示例:

@Aspect
@Component
public class LoggingAspect {
    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore() {
        System.out.println("执行方法前打印日志");
    }
}

📌 作用:

  • 事务管理(@Transactional):Spring 通过代理模式在方法前后添加事务处理逻辑。

(5)适配器模式(Adapter Pattern)

Spring 使用 适配器模式 来统一不同接口,保持代码灵活性。

Spring 相关实现:

  • HandlerAdapter:适配不同类型的 Controller(如 @RequestMapping@RestController)。
  • ViewResolver:适配不同视图解析,如 JSP、Thymeleaf、JSON 等。

示例:

@RequestMapping("/hello")
public String hello() {
    return "Hello Spring!";
}

📌 RequestMappingHandlerAdapter 适配不同的 @Controller 处理方法。


(6)装饰器模式(Decorator Pattern)

Spring 采用 装饰器模式 来增强功能,如 BeanPostProcessor、HandlerInterceptor

Spring 相关实现:

  • HandlerInterceptor:拦截请求并增强功能(如鉴权)。
  • BeanPostProcessor:在 Bean 初始化前后执行逻辑。

示例:

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("Bean 初始化前:" + beanName);
        return bean;
    }
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("Bean 初始化后:" + beanName);
        return bean;
    }
}

3. 行为型模式(Behavioral Patterns)

(7)观察者模式(Observer Pattern)

Spring 事件机制基于 观察者模式,用于 组件间解耦事件通知

Spring 相关实现:

  • ApplicationEvent(事件)
  • ApplicationListener(监听器)

示例:

@Component
public class MyEventListener implements ApplicationListener<ApplicationEvent> {
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("监听到事件:" + event);
    }
}

📌 Spring 内置事件:

  • ContextRefreshedEvent(容器刷新)
  • ContextClosedEvent(容器关闭)

(8)模板方法模式(Template Method Pattern)

Spring 简化 JDBC 操作,使用 模板方法模式 让子类重写关键步骤,而公共部分由父类实现。

Spring 相关实现:

  • JdbcTemplate
  • RestTemplate
  • TransactionTemplate

示例:

jdbcTemplate.query("SELECT * FROM users", (rs, rowNum) -> new User(rs.getInt("id"), rs.getString("name")));

📌 Spring 处理连接、异常,开发者只需专注 SQL 逻辑


(9)策略模式(Strategy Pattern)

Spring 采用 策略模式 来动态选择不同的算法或实现方案。

Spring 相关实现:

  • Resource 访问策略(支持 FileSystem、Classpath、URL 等不同资源访问方式)
  • TransactionManager 事务管理策略(JpaTransactionManagerDataSourceTransactionManager

示例:

public interface PaymentStrategy {
    void pay(int amount);
}
@Component
public class WeChatPay implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("使用微信支付:" + amount);
    }
}
@Component
public class AliPay implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("使用支付宝支付:" + amount);
    }
}

Spring 通过 @Autowired 依赖注入 动态选择支付方式


🎯 总结

设计模式Spring 应用场景
工厂模式BeanFactoryApplicationContext
单例模式Spring Bean 默认单例
原型模式@Scope("prototype")
代理模式AOP(事务、日志)
适配器模式HandlerAdapter
装饰器模式BeanPostProcessor
观察者模式ApplicationListener 事件机制
模板方法模式JdbcTemplate
策略模式TransactionManagerResource
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值