简单的模块结构
project 项目
└── repository 模块
└── service 模块
└── controller 模块
其中 controller 依赖 service 和repository 模块,service 模块依赖 repository 模块。项目使用idea 来创建
创建项目

springboot 项目默认选择的是Maven Project ;多模块项目一定要选择 Maven POM

选择好需要的依赖后,finish。

项目界面

开始创建子模块

此时需要选择Maven 项目,输入模块名即可。依次创建3个模块。
可以看到idea已经自动为我们将3个模块添加到项目了

在模块中添加相关依赖 和 启动类及application.yml 文件
controller
—pom.xml
<dependencies>
<!-- 依赖dao 和service模块-->
<dependency>
<groupId>com.example</groupId>
<artifactId>dao</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>service</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MultipleModuleApplication {
public static void main(String[] args) {
SpringApplication.run(MultipleModuleApplication.class,args);
}
}
application.yml
server:
port: 8081
spring:
datasource:
url: jdbc:h2:mem:example-app;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
password:
driver-class-name: org.h2.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: update
database-platform: org.hibernate.dialect.H2Dialect
h2:
console:
enabled: true
path: /console
settings:
trace: false
web-allow-others: false
service 模块
—pom.xml
<dependencies>
<!-- 依赖dao模块-->
<dependency>
<groupId>com.example</groupId>
<artifactId>dao</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
注意事项
1、如果entity和repository、compent 相关类不在controller 模块下,springboot自动扫描时是扫不到这些相关类。此时需要在启动类上加上@EntityScan(basePackages = "")和@EnableJpaRepositories(basePackages = "") 和@ComponentScan(basePackages = "") ,这个三个注解中basePackages 的值就是相关类所在的包,如果在多个包下时,可以统一这些包的首包名,使用通配符*来扫描所有的包,如basePackages = "com.*"。因为@SpringBootApplication注解中已经包含的@CompentScan,所以可以不用添加@CompentScan,直接使用@SpringBootApplication(basePackages="")来添加。
@SpringBootApplication
@EntityScan(basePackages = "com.*")
@ComponentScan(basePackages = "com.*")
@EnableJpaRepositories(basePackages = "com.*")
public class MultipleModuleApplication {
public static void main(String[] args) {
SpringApplication.run(MultipleModuleApplication.class,args);
}
}
2、打包
mvn clean package -Dmaven.test.ski=true
此时肯定打包失败,
需要将在parent pom 文件下的
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
移动到controller模块下的pom.xml ,parent模块下则不在保留。
源码链接:https://github.com/miskss/SpringBootMultipleModule
git:https://github.com/miskss/SpringBootMultipleModule.git
本文详细介绍如何使用SpringBoot创建多模块项目,包括项目结构、模块依赖、配置及常见问题解决。通过具体步骤,读者可了解如何在Idea中创建并配置多模块项目,以及如何正确设置模块间的依赖关系。
21万+

被折叠的 条评论
为什么被折叠?



