You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将配置层从按层分包迁移至按功能分包?

按功能分包重构@Configuration文件的实现方案

背景

已完成业务代码从按层分包到按功能分包的迁移,但原configuration包仍保留按层模式,需将配置文件按功能归属拆分,避免混合分包模式。各配置的依赖关系明确:

  • KafkaProducerConfiguration:仅为CompanyService提供消息发送配置
  • RestClientConfiguration:为UserService和ProductService提供外部查询的客户端配置
  • MongoRepositoryConfiguration:为三个业务模块的Repository提供通用Mongo配置

核心重构原则

按配置的功能归属拆分:专属某业务模块的配置归入对应功能包;多模块共享的配置归入公共功能包。

具体重构步骤

  1. 专属业务模块的配置迁移

    • 将KafkaProducerConfiguration迁移至com.app.company.config包下,因它仅服务于Company业务模块。
  2. 跨模块共享配置的处理

    • 对于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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:27:24