如何将配置层从按层分包迁移至按功能分包?
按功能分包重构@Configuration文件的实现方案
背景
已完成业务代码从按层分包到按功能分包的迁移,但原configuration包仍保留按层模式,需将配置文件按功能归属拆分,避免混合分包模式。各配置的依赖关系明确:
KafkaProducerConfiguration:仅为CompanyService提供消息发送配置RestClientConfiguration:为UserService和ProductService提供外部查询的客户端配置MongoRepositoryConfiguration:为三个业务模块的Repository提供通用Mongo配置
核心重构原则
按配置的功能归属拆分:专属某业务模块的配置归入对应功能包;多模块共享的配置归入公共功能包。
具体重构步骤
专属业务模块的配置迁移
- 将
KafkaProducerConfiguration迁移至com.app.company.config包下,因它仅服务于Company业务模块。
- 将
跨模块共享配置的处理
- 对于
RestClientConfiguration:- 若为两个模块共用的通用配置,新建
com.app.shared.config公共包存放; - 若为分别适配User、Product业务的定制化客户端配置,则拆分为
UserRestClientConfiguration和ProductRestClientConfiguration,分别归入com.app.user.config和com.app.product.config。
- 若为两个模块共用的通用配置,新建
- 对于
MongoRepositoryConfiguration:属于全模块共享的数据访问基础配置,归入com.app.shared.config公共包。
- 对于
最终目录结构
├── com.app └── company ├── config │ └── KafkaProducerConfiguration ├── Company ├── CompanyController ├── CompanyRepository └── CompanyService └── product ├── config │ └── ProductRestClientConfiguration(若为定制化) ├── Product ├── ProductController ├── ProductRepository └── ProductService └── user ├── config │ └── UserRestClientConfiguration(若为定制化) ├── User ├── UserController ├── UserRepository └── UserService └── shared └── config ├── MongoRepositoryConfiguration └── RestClientConfiguration(若为通用型)
注意事项
- 若共享配置后续出现业务定制化需求,可随时拆分到对应功能包,保持灵活性。
- 确保Spring能扫描到所有配置类:可在启动类添加
@ComponentScan(basePackages = "com.app"),或保留各配置类的@Configuration注解,Spring默认会扫描启动类所在包及子包。
内容的提问来源于stack exchange,提问作者PatPanda
相关产品推荐
相关产品推荐

