1. 程式人生 > >Spring Boot 2.0.1 入門教程

Spring Boot 2.0.1 入門教程

代碼生成 -i Coding fig IT code location sta -a

簡介

Spring Boot是Spring提供的一套基礎配置環境,可以用來快速開發生產環境級別的產品。尤其適合開發微服務架構,省去了不少配置麻煩。比如用到Spring MVC時,只需把spring-boot-starter-web依賴添加到Maven依賴中即可。另外它還有如下特性:

  • 創建獨立的Spring項目
  • 內置Tomcat, Jetty,Undertow
  • 初始POM配置文件以簡化Maven配置
  • 盡可能的自動配置Spring
  • 提供生產環境功能,如統計,健康檢查和外部配置
  • 無需XML配置和代碼生成

創建 Spring Boot 應用

  • 開發環境:IntelliJ, JDK 1.8
  • 項目源代碼 Gitee

首先在IntelliJ中創建一個maven項目:

  • GroupID: cn.zxuqian
  • ArtifactId: helloworld

創建完成後IntelliJ右下角會提示自動導入Maven配置,選擇Enable Auto-Import來啟動自動導入。然後在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"> <modelVersion>4.0.0</modelVersion> <groupId>cn.zxuqian</groupId> <artifactId>helloworld</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>
org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

<dependencies> 標簽添加了spring-boot-starter-web依賴,即 Spring MVC 和相關運行時環境。spring-boot-maven-plugin插件提供了一組maven運行目標,可以方便的打包,部署和運行應用。稍等片刻Maven自動下載依賴後就可以上手寫代碼了。

創建第一個控制器

src/main 下新建一個包 cn.zxuqian.controllers 並在其中新建一個類,名為 HelloController 並添加如下代碼:

package cn.zxuqian.controllers;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/")
    public String index() {
        return "Hello World!";
    }
    
}
  • @RestController 標記此類為 Rest 控制器,並準備好處理 Rest 請求。
  • @RequestMapping("/") 即此方法處理根路徑請求,如 http://localhost:8080/
  • index 方法返回 String 類型,即響應返回的是字符串數據,這裏是 "Hello World"。

創建 Application 類

cn.zxuqian 包下創建 Application 類,並添加如下代碼:

package cn.zxuqian;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  • @SpringBootApplication 標明了此類為 Spring Boot 應用的啟動類。

運行應用

在IntelliJ的右側選項卡中選擇 Maven Projects,然後展開 Plugins-->spring-boot,選擇 spring-boot:run 目標。待啟動成功後,在瀏覽器中訪問 http://localhost:8080 看到 Hello World! 即為成功。

文章出自我的博客:http://zxuqian.cn/spring-boot-get-started/,歡迎訪問。

Spring Boot 2.0.1 入門教程