天天看點

Spring Boot 項目建立

3 種方式實作 Spring Boot 項目建立。

1 官方網站線上建立

官方網站:https://start.spring.io/,如下:

Spring Boot 項目建立

配置說明如下:

  • Project:項目建構工具,這裡選擇 Maven ,Gradle 一般在 Android 中使用較多。
  • Language:開發語言,這裡選擇 Java 。
  • Spring Boot:版本,一般用最新穩定版。
  • Project Metadata:Maven 工程相關資訊,如項目坐标、項目描述等。Packing 表示項目打包方式,這裡選擇 jar 包,因為 Spring Boot 内嵌了 Servlet 容器,打成 jar 包即可直接運作,當然也可根據實際情況選擇 war 包。Java 表示選擇建構的 JDK 版本。
  • Dependencies:選擇所需要的依賴,這裡先加入 web 依賴,可通過關鍵字搜尋。

最後點選下面的按鈕生成并導出後,用 IntelliJ IDEA 或者 Eclipse 打開繼續開發。

2 IDE 建立

這裡示範使用 IntelliJ IDEA 作為 IDE 來建立。

File -> New Project -> Spring Initializr 。

可以看到這裡實際上也是用了官方網站的位址來建立,隻是 IntelliJ IDEA 把裡面的東西內建進來了。

Spring Boot 項目建立

填寫 Maven 工程相關資訊:

Spring Boot 項目建立

選擇依賴:

Spring Boot 項目建立

填寫項目相關資訊:

Spring Boot 項目建立

3 Maven 建立

File -> New Project -> Maven 。

選擇項目骨架(我這裡不選擇,有興趣的可以試下裡面的 Spring Boot 相關項目骨架):

Spring Boot 項目建立

填寫 Maven 工程相關資訊:

Spring Boot 項目建立

填寫項目相關資訊:

Spring Boot 項目建立

建立完成後,打開 pom.xml 添加依賴:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
</parent>

<dependencies>
    <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>
           

接着在

com.cxy35.sample.springboot.helloworld

包中建立啟動類

SpringBootHelloworldApplication.java

@SpringBootApplication
public class SpringBootHelloworldApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootHelloworldApplication.class, args);
    }

}
           

4 啟動項目測試

com.cxy35.sample.springboot.helloworld.controller

包中建立測試類

HelloController.java

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello spring boot!";
    }
}
           

運作

SpringBootHelloworldApplication.java

中的 main 方法啟動項目,浏覽器通路 http://127.0.0.1:8080/hello 測試。

最終的項目結構如下:

Spring Boot 項目建立
  • Spring Boot 教程合集(微信左下方閱讀全文可直達)。
  • Spring Boot 教程合集示例代碼:https://github.com/cxy35/spring-boot-samples
  • 本文示例代碼:https://github.com/cxy35/spring-boot-samples/tree/master/spring-boot-helloworld

掃碼關注微信公衆号 程式員35 ,擷取最新技術幹貨,暢聊 #程式員的35,35的程式員# 。獨立站點:https://cxy35.com

Spring Boot 項目建立

繼續閱讀