网站首页 > 技术文章 正文
Spring 的策略模式通过接口抽象和依赖注入,将算法或行为的选择权从调用方彻底解耦。它在事务管理、缓存策略、支付集成等场景中广泛应用,是 Spring 框架高扩展性的核心设计思想之一。掌握策略模式的实现方式与 Spring 的集成技巧(如条件注解、Map 注入),能显著提升代码的模块化水平和可维护性。
1. Spring 策略模式的核心特点
算法可互换:通过统一接口定义策略,具体实现可动态替换(如支付方式、缓存策略)。
解耦策略定义与使用:调用方依赖抽象策略接口,无需关心具体实现细节。
与容器集成:利用 Spring 的依赖注入机制,通过配置或条件注解动态选择策略。
扩展性:新增策略只需实现接口并注册为 Bean,无需修改现有代码。
2. Spring 版本与源码获取
版本:Spring Framework 5.3.26(长期支持版本)
源码下载:
Maven 依赖:
org.springframework
spring-context
5.3.26
直接下载地址:Spring Framework 5.3.26 Release
git clone https://github.com/spring-projects/spring-framework.git
cd spring-framework
git checkout tags/5.3.26.RELEASE
调试技巧:
关键断点位置:
DefaultListableBeanFactory.getBean() → determinePrimaryCandidate()(策略优先级判断)。
观察策略接口的实现类(如
PlatformTransactionManager 的多个实现)。
3. 源码级实现剖析
策略接口像“武器插槽”,具体策略是“不同武器”(如剑、弓箭),战士(调用方)根据战场需求随时更换武器。
// 策略接口示例:PlatformTransactionManager
public interface PlatformTransactionManager extends TransactionManager {
TransactionStatus getTransaction(@Nullable TransactionDefinition definition);
void commit(TransactionStatus status);
void rollback(TransactionStatus status);
}
// 具体策略实现类:DataSourceTransactionManager(JDBC 事务)
public class DataSourceTransactionManager extends AbstractPlatformTransactionManager {
@Override
protected Object doGetTransaction() { /* JDBC 事务实现 */ }
}
// 具体策略实现类:JpaTransactionManager(JPA 事务)
public class JpaTransactionManager extends AbstractPlatformTransactionManager {
@Override
protected Object doGetTransaction() { /* JPA 事务实现 */ }
}
4. 策略模式的多维度应用
配置方式对比
XML 配置:
注解配置:
@Component
@Primary // 标记默认策略
public class AlipayStrategy implements PaymentStrategy { ... }
@Service
public class PaymentService {
@Autowired // 自动注入默认策略
private PaymentStrategy paymentStrategy;
}
条件化策略选择:
@Bean
@ConditionalOnProperty(name = "cache.type", havingValue = "redis")
public CacheStrategy redisCache() { return new RedisCacheStrategy(); }
@Bean
@ConditionalOnProperty(name = "cache.type", havingValue = "local")
public CacheStrategy localCache() { return new LocalCacheStrategy(); }
策略动态切换
@Component
public class PaymentContext {
private final Map strategyMap;
// 注入所有 PaymentStrategy 实现(Key 为 Bean 名称)
public PaymentContext(Map strategyMap) {
this.strategyMap = strategyMap;
}
public void pay(String strategyName, BigDecimal amount) {
PaymentStrategy strategy = strategyMap.get(strategyName);
strategy.execute(amount);
}
}
5. 策略模式 vs 其他模式
场景 | 策略模式 | 工厂模式 | 模板方法模式 |
关注点 | 算法/行为的动态替换 | 对象的创建过程封装 | 算法骨架的复用与扩展 |
Spring 集成 | 通过依赖注入实现策略切换 | 通过 BeanFactory 创建对象 | 通过抽象类定义模板方法 |
典型应用 | 支付方式、缓存策略、事务管理 | Bean 实例化、复杂对象构建 | JDBC 操作、HTTP 请求处理 |
6. 实际应用场景
多支付网关集成:
public interface PaymentStrategy {
void pay(BigDecimal amount);
}
@Component("alipay")
public class AlipayStrategy implements PaymentStrategy { ... }
@Component("wechat")
public class WechatPayStrategy implements PaymentStrategy { ... }
国际化消息解析:
public interface LocaleResolver {
Locale resolveLocale(HttpServletRequest request);
}
// CookieLocaleResolver 和 SessionLocaleResolver 实现不同解析策略
缓存策略切换:
@Bean
@ConditionalOnProperty(name = "app.cache", havingValue = "redis")
public CacheService redisCacheService() { ... }
@Bean
@ConditionalOnProperty(name = "app.cache", havingValue = "caffeine")
public CacheService caffeineCacheService() { ... }
7. 源码调试与陷阱规避
调试步骤:
- 在 DefaultListableBeanFactory.getBean() 设置断点,观察策略 Bean 的加载过程。
- 通过 @Conditional 注解的条件判断逻辑(如 OnPropertyCondition)。
常见陷阱:
策略冲突:多个策略 Bean 未标记 @Primary 导致注入失败(需明确指定 @Qualifier)。
作用域问题:策略 Bean 若为原型(Prototype),需确保每次调用时重新获取。
循环依赖:策略实现类之间相互引用可能导致启动失败(需重构代码或使用 @Lazy)。
8. 性能与最佳实践
优点:
- 提升代码灵活性和可测试性(易于 Mock 策略实现)。
- 支持运行时动态切换策略(如根据配置切换缓存实现)。
优化建议:
- 避免过度设计:简单场景可直接用 if-else,复杂场景再引入策略模式。
- 策略预加载:对高频使用的策略对象缓存实例(如结合单例作用域)。
- 统一异常处理:在策略接口中定义统一的异常类型,便于错误处理。
- 上一篇: Spring框架功能分为哪些模块?
- 下一篇: SpringBoot框架
猜你喜欢
- 2025-03-10 深度剖析 Spring:程序员不可或缺的开发利器
- 2025-03-10 浅谈业务解耦小工具 - Spring Event
- 2025-03-10 Nice,终于有人把SpringMVC讲明白了,太简单了...
- 2025-03-10 如何理解Spring框架的重要特性:AOP
- 2025-03-10 Java开发中常用的框架有哪些?
- 2025-03-10 二十八、Spring 中的代理模式深度解析
- 2025-03-10 SpringBoot框架
- 2025-03-10 Spring框架功能分为哪些模块?
- 2025-03-10 Spring框架详解
- 2025-03-10 万变不离其宗,spring常考知识点总结
- 03-10深度剖析 Spring:程序员不可或缺的开发利器
- 03-10浅谈业务解耦小工具 - Spring Event
- 03-10Nice,终于有人把SpringMVC讲明白了,太简单了...
- 03-10如何理解Spring框架的重要特性:AOP
- 03-10Java开发中常用的框架有哪些?
- 03-10二十八、Spring 中的代理模式深度解析
- 03-10SpringBoot框架
- 03-10三十一、Spring 中的策略模式深度解析
- 最近发表
- 标签列表
-
- cmd/c (57)
- c++中::是什么意思 (57)
- sqlset (59)
- ps可以打开pdf格式吗 (58)
- phprequire_once (61)
- localstorage.removeitem (74)
- routermode (59)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- log.warn (60)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- resttemplateokhttp (59)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- reader.onload (61)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- java是值传递还是引用传递 (58)
- 无效的列索引 (74)