spring boot 多模块项目的构建以及配置文件的读取

 

 

在目前的开发过程中,我们有一个服务需要用到第三方的硬件API,目前初步的想法是把这块服务单独做成一个模块来集成到项目中。那么就会涉及到springboot项目多模块构建,打包的问题。在此分享一下我填坑的解决办法。让我们开始吧。

基本配置:

1.创建父文件项目multiboot

在IDEA开发工具中,采用spring Initializr新建项目时生成的项目结构如下:

红框中的文件都是没必要的,为了项目看起来整洁,我们将其删除,同时src目录也是没用的,我们只留下如下的目录结构:

2.将其父级设置为Spring Boot启动父级:

<project...>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version&
为了避免Spring Boot模块中的配置或依赖影响到非Spring Boot模块,可以采取以下几种策略: 1. **使用 profiles**:Spring Boot支持多种构建模式,比如在父POM中设置一个`spring-boot` profile,在这个profile下启用Spring Boot相关的配置和插件。在非Spring Boot模块的子POM中,通过`<properties>`或`<profiles>`标签禁用该profile。 ```xml <!-- 父POM配置 --> <profiles> <profile> <id>spring-boot</id> <activation> <activeByDefault>true</activeByDefault> </activation> <modules> <!-- 包含所有Spring Boot模块 --> </modules> </profile> <!-- 其他profile可以包含非Spring Boot模块 --> <profile> <id>non-spring-boot</id> <modules> <!-- 非Spring Boot模块列表 --> </modules> </profile> </profiles> <!-- 子POM配置 --> <profiles> <profile> <id>spring-boot</id> <activation> <property> <name>!spring.boot.active</name> </property> </activation> <!-- 添加Spring Boot依赖,如: --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies> </profile> <!-- 同时定义一个非激活的Spring Boot profile --> <profile> <id>spring.boot.non-active</id> </profile> </profiles> ``` 2. **按需添加依赖**:在非Spring Boot模块的`pom.xml`中,仅添加实际需要的依赖,而不应默认引入整个Spring Bootstarter套件。 3. **分层管理**:如果非Spring Boot模块依赖于Spring Boot提供的库,可以考虑使用模块化的方式,让它们分别作为独立的库被引用。 4. **配置分离**:将Spring Boot配置文件(如application.properties或yml)从父项目移到每个模块的src/main/resources目录下,这样只有Spring Boot模块才会读取它们。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值