創建項目
創建一個 SpringBoot 項目非常的簡單,簡單到這里根本不用再提。你可以在使用 IDEA 新建項目時直接選擇 Spring Initlalize
創建一個 Spring Boot 項目,也可以使用 Spring 官方提供的 Spring Boot 項目生成頁面得到一個項目。
下面介紹一下使用 Spring 官方生成的方式,如果你已經有了一個 Spring Boot 項目,這部分可以直接跳過。
-
打開 https://start.spring.io/
-
填寫
group
和Artifact
信息,選擇依賴(我選擇了 Spring Web 和 Lombok )。 -
點擊
Generate
按鈕下載項目。 -
打開下載的項目,刪除無用的
.mvn
文件夾,mvnw
、mvnw.cmd
、HELP.md
文件。
到這里已經得到了一個 Spring Boot 初始項目了,我們直接導入到 IDEA 中,看一眼 pom.xml
的內容。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/><!-- lookup parent from repository -->
</parent>
<groupId>com.wdbyte</groupId>
<artifactId>springboot-module-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-module-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
把目錄結構調整成自己想要的結構,然后添加 controller
和 entity
用於測試。
ProductController 類源代碼。
@RestController
@RequestMapping("/product")
publicclass ProductController {
/**
* 獲取商品列表
*
* @return
*/
@GetMapping("/list")
public Map list() {
// 模擬查詢商品邏輯
Product product = new Product();
product.setProductName("小米粥");
product.setProductPrice(new BigDecimal(2.0));
product.setProductStock(100);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("code", 000);
resultMap.put("message", "成功");
resultMap.put("data", Arrays.asList(product));
return resultMap;
}
}
Product 類源代碼。
@Data
publicclass Product {
/** 商品名稱. */
private String productName;
/** 商品價格. */
private BigDecimal productPrice;
/** 商品庫存。*/
privateint productStock;
}
模塊化
借助 IDEA 工具可以快速的把項目改造成 maven 多模塊,這里我們把准備測試 demo 拆分為 common 和 web 兩個模塊,common 模塊存放實體類。web 模塊存放 controller 層(這里項目雖小,拆分只是為了演示)。話不多說,直接開始。
-
配置主 pom.xml 打包方式 為 pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 配置主 pom 打包方式為 pom -->
<packaging>pom</packaging>
....
.... -
創建 common 模塊
項目直接 new -> module。
選擇 maven -> next,填寫模塊名稱。
繼續 next 完成模塊創建。
-
創建 web 模塊
web 模塊的創建和 common 模塊如出一轍,不再贅述。完成兩個模塊的創建之后,你會發現你的主 pom.xml 文件里自動添加了 module 部分。
<modules>
<module>product-common</module>
<module>product-web</module>
</modules> -
移動代碼到指定模塊
移動
Product.java
到product-common
模塊,其他部分代碼和 resource 部分直接移動到product-web
模塊,移動完后你的代碼結構是這個樣子。
到這里,多模塊已經拆分完成了, 但是 ProductController
代碼里的紅色警告讓你發現事情還沒有結束。
依賴管理
處理依賴問題
你發現了代碼里的紅色警告,不過你也瞬間想到了是因為把 Product
類移動到了 product-common
模塊,導致這里引用不到了。
然后你查看了下 product-common
模塊的 pom.xml 里的內容。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-module-demo</artifactId>
<groupId>com.wdbyte</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product-common</artifactId>
</project>
機智的在 Product-web
模塊的 pom.xml 里引入 product-common,手起鍵落,輕松搞定。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-module-demo</artifactId>
<groupId>com.wdbyte</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product-web</artifactId>
<dependencies>
<dependency>
<groupId>com.wdbyte</groupId>
<artifactId>product-common</artifactId>
</dependency>
</dependencies>
</project>
滿心歡喜的你快速的點擊 Build-> Build Project,得到的 Error 警告刺痛了頂着黑眼圈的你。
不過你還是迅速定位了問題,查看 maven 依賴,你發現是因為沒有指定 product-common
依賴的版本號。
原來如此,因為沒有指定版本號,我們指定上不就完事了嘛。在最外層的主 pom.xml 中添加 <dependencyManagement>
添加上指定依賴和要指定的版本號。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.wdbyte</groupId>
<artifactId>product-common</artifactId>
<version>0.0.1-SNAPSHOT</version><!-- maven 打包默認 0.0.1-SNAPSHOT 版本 -->
</dependency>
</dependencies>
</dependencyManagement>
刷新 maven ,發現項目已經不報錯了,編譯成功,運行啟動類,熟悉的 Spring logo 又出現在眼前。
優化依賴
是的,Spring Boot 應用在改造成多模塊后成功運行了起來,但是你貌似發現一個問題,模塊 common
和模塊 web
都繼承了主 pom ,主 pom 中有 Lombok 、Spring Boot Web 和 Spring Boot Test 依賴,而 common
模塊里只用到了 Lombok 啊,卻一樣繼承了 Spring Boot 其他依賴,看來還是要改造一把。
-
只有
common
模塊用到的依賴移動到common
模塊。<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-module-demo</artifactId>
<groupId>com.wdbyte</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product-common</artifactId>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project> -
只有
web
模塊用到的依賴移動到web
模塊。<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-module-demo</artifactId>
<groupId>com.wdbyte</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product-web</artifactId>
<dependencies>
<dependency>
<groupId>com.wdbyte</groupId>
<artifactId>product-common</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project> -
抽取用到的版本號到
<properties>
,這里抽取common
模塊的依賴版本。到這里最外層主 pom 的內容是這樣的。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<modules>
<module>product-common</module>
<module>product-web</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/><!-- lookup parent from repository -->
</parent>
<groupId>com.wdbyte</groupId>
<artifactId>springboot-module-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-module-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<product-common.version>0.0.1-SNAPSHOT</product-common.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.wdbyte</groupId>
<artifactId>product-common</artifactId>
<version>${product-common.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
看似完美,重新 Build-> Build Project ,發現一切正常,運行發現一切正常,訪問正常。
打包編譯
好了,終於到了最后一步了,你感覺到勝利的曙光已經照到了頭頂,反射出耀眼的光芒。接着就是 mvn package
。
[INFO] springboot-module-demo ............................. SUCCESS [ 2.653 s]
[INFO] product-common ..................................... FAILURE [ 2.718 s]
[INFO] product-web ........................................ SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.084 s
[INFO] Finished at: 2020-03-19T08:15:52+08:00
[INFO] Final Memory: 22M/87M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.2.5.RELEASE:repackage (repackage) on project product-common: Execution repackage of goal org.springframework.boot:spring-boot-m
aven-plugin:2.2.5.RELEASE:repackage failed: Unable to find main class -> [Help 1]
[ERROR]
ERROR 讓你傷心了,但是你還是從報錯中尋找到了一些蛛絲馬跡,你看到是 spring-boot-maven-plugin 報出的錯誤。重新審視你的主 pom 發現 <build>
編譯插件用到了 spring-boot-maven-plugin。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
略加思索后將這段移動到 web
模塊的 pom,因為這是 Spring Boot 的打包方式,現在放在主 pom 中所有的模塊都會繼承到,那么對於 common
模塊來說是肯定不需要的。
移動后重新打包,不管你是運行命令 mvn package
還是雙擊 IDEA 中的 maven 管理中的 package ,想必這時候你都已經打包成功了
在 web
模塊下的目錄 target 里也可以看到打包后的 jar 文件 product-web-0.0.1-SNAPSHOT.jar。可以使用 java 命令直接運行。
$ \springboot-module-demo\product-web\target>java -jar product-web-0.0.1-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.5.RELEASE)
2020-03-19 08:33:03.337 INFO 15324 --- [ main] com.wdbyte.Application : Starting Application v0.0.1-SNAPSHOT on DESKTOP-8SCFV4M with PID 15324 (C:\Users\83981\Desktop\springboot-mod
ule-demo\product-web\target\product-web-0.0.1-SNAPSHOT.jar started by 83981 in C:\Users\83981\Desktop\springboot-module-demo\product-web\target)
2020-03-19 08:33:03.340 INFO 15324 --- [ main] com.wdbyte.Application : No active profile set, falling back to default profiles: default
2020-03-19 08:33:04.410 INFO 15324 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-19 08:33:04.432 INFO 15324 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-19 08:33:04.432 INFO 15324 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-03-19 08:33:04.493 INFO 15324 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-19 08:33:04.493 INFO 15324 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1107 ms
2020-03-19 08:33:04.636 INFO 15324 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-19 08:33:04.769 INFO 15324 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-19 08:33:04.772 INFO 15324 --- [ main] com.wdbyte.Application : Started Application in 1.924 seconds (JVM running for 2.649)
2020-03-19 08:33:07.087 INFO 15324 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
想必少了點什么,多模塊不僅為了結構清晰,更是為了其他項目可以復用模塊(如 common 模塊),現在這個時候如果你新打開了一個項目,依賴 common
發現是引用不到的,因為你需要把模塊安裝到本地倉庫。可以點擊 IDEA -> Maven -> install,也可以通過 maven 命令。
# -Dmaven.test.skip=true 跳過測試
# -U 強制刷新
# clean 清理緩存
# install 安裝到本地倉庫
$ \springboot-module-demo> mvn -Dmaven.test.skip=true -U clean install
重新引入發現沒有問題了。
文中代碼已經上傳到 Github:niumoo/springboot