goeingPrintServer/CIRCULAR_DEPENDENCY_SOLUTION.md
2025-07-01 10:01:07 +08:00

58 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 循环依赖解决方案
## 当前问题
在应用程序上下文中存在循环依赖:
```
┌─────┐
| printController (field private com.goeing.printserver.main.service.PrintQueueService com.goeing.printserver.main.PrintController.printQueueService)
↑ ↓
| printQueueService (field private com.goeing.printserver.main.PrintController com.goeing.printserver.main.service.PrintQueueService.printController)
└─────┘
```
## 临时解决方案
已在 `application.properties` 中添加以下配置,临时允许循环依赖:
```properties
spring.main.allow-circular-references=true
```
## 已实施的重构步骤
1. 创建了 `PrintService` 接口,定义打印相关操作
2. 修改 `PrintController` 实现 `PrintService` 接口
3. 修改 `PrintQueueService` 依赖 `PrintService` 而不是直接依赖 `PrintController`
## 后续重构建议
为彻底解决循环依赖问题,建议进一步重构:
### 方案一:使用事件驱动架构
1. 使用 Spring 的事件机制ApplicationEventPublisher替代直接方法调用
2. `PrintQueueService` 发布打印事件
3. `PrintController` 订阅并处理这些事件
### 方案二:引入服务层抽象
1. 创建更完整的服务层抽象,明确职责分离
2.`PrintController` 中的业务逻辑移至专门的服务类
3.`PrintController``PrintQueueService` 都依赖这个新服务类
### 方案三:重新设计组件职责
1. 重新评估 `PrintController``PrintQueueService` 的职责
2. 可能的职责划分:
- `PrintController`:仅处理 HTTP 请求和响应
- `PrintQueueService`:管理打印队列和执行打印操作
- 新增 `PrintExecutionService`:实际执行打印操作的逻辑
## 最佳实践
- 遵循单一职责原则,每个类只负责一个功能领域
- 使用依赖注入,但避免双向依赖
- 考虑使用事件驱动架构处理组件间通信
- 使用接口进行解耦,降低组件间直接依赖