1. 程式人生 > >Spring Boot 2.0 之 Hello World

Spring Boot 2.0 之 Hello World

    Spring Boot 簡化了 Spring 的操作, 不需要配置就能執行 Spring 應用. Spring Boot 管理 spring 容器、第三方外掛, 並提供很多預設系統級的服務. Spring Boot 通過 Starter 來提供系統級服務. 

    相比於 Spring, Spring Boot 具有以下的特點:

    ①: 實現約定大於配置,是一個低配置的應用級框架. 不像 Spring 那樣需要大量的配置. Spring Boot 不需要配置或者極少配置,就能使用 Spring 大量的功能.

    ②: 提供了內建的 Tomcat 或者 Jetty 容器.

    ③: 通過依賴的 jar 包管理、自動裝配技術, 容易支援與其他技術體系、工具整合.

    ④: 支援熱載入, 開發體驗較好. 也支援 Spring Boot 系統監控, 方便了解系統執行情況.

 

Hello Spring Boot 2.0;

POM 配置:

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
</parent>

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
</dependencies>
<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
</build>

 啟動類:

package com.pangu.helloworld;

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

@SpringBootApplication
public class HelloWorldApplication {

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

}

 Controller:

package com.pangu.helloworld;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloWorldController {
    
    @RequestMapping("/index")
    @ResponseBody
    public String index(){
        return "你好 Spring Boot 2.0.";
    }
    
}

結果:

RESTFul 風格:

package com.pangu.helloworld;

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

/**
 * @ClassName: HelloWorldRESTFulController
 * @Description: TODO RESTFul 架構風格
 * @author etfox
 * @date 2018年10月5日 下午8:41:37
 *
 * @Copyright: 2018 www.etfox.com Inc. All rights reserved.
 */
@RestController
public class HelloWorldRESTFulController {
    
    @RequestMapping("/rest/{id}")
    public String rest(@PathVariable String id){
        return id;
    }
    
}

結果:

 另:熱部署>>>>>>>>>>>>>>

<!-- 熱部署 -->
	<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
	</dependencies>

修改 pom.xml  後,此後啟動專案,修改可免重啟編譯. 主要多了幾個變化:LiveReload server 監控 Spring Boot 應用的變化,另外啟動時間變為 0.5 秒, 因為他避免了重啟 Spring Boot 應用, 也避免重新載入 Spring 的類, 只重新載入修改的類.