手動建立標準 Maven 目錄結構,核心 pom.xml 如下:
<project ...>
<modelVersion>4.0.0</modelVersion>
<groupId>com.xxx</groupId>
<artifactId>myboot</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 方式一:繼承 spring-boot-starter-parent(最簡單) -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 打包為可執行 JAR -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
改用 dependencyManagement 引入 BOM:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.2.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
同時需在 spring-boot-maven-plugin 中額外配置 <configuration><mainClass>...</mainClass></configuration> 指定啟動類。
@RestController
@EnableAutoConfiguration
public class FirstBoot {
@RequestMapping("/hello")
public String testFirstMethod() {
return "Hello jigang!!!";
}
public static void main(String[] args) {
SpringApplication.run(FirstBoot.class, args);
}
}
@RestController = @Controller + @ResponseBody,直接返回 JSON。@EnableAutoConfiguration:啟用 Spring Boot 自動配置核心。main 方法。mvn spring-boot:run(會下載依賴)Run As → Java ApplicationTomcat started on port(s): 8080 即成功。https://localhost:8080/hello 返回 Hello jigang!!!。注意:首次請求時才初始化 DispatcherServlet(按需啟動)。
mvn package
target/ 下產生兩個 JAR:
myboot-1.0-SNAPSHOT.jar:Spring Boot 重新打包(repackage),含所有依賴,**可直接執行**。myboot-1.0-SNAPSHOT.jar.original:Maven 原始輸出。執行:java -jar target/myboot-1.0-SNAPSHOT.jar。
