1. 程式人生 > >[Spring Boot] 一、使用Spring Boot建立一個應用

[Spring Boot] 一、使用Spring Boot建立一個應用

最近要做一個客戶端的活,準備使用輕量級的Spring Boot來完成,記錄整個Spring Boot學習過程

  1. 需要準備的內容

    • JDK 1.8 or later
    • 一個IDE,我習慣於使用Intellij Idea
    • Maven
  2. 克隆Github上的Demo

    $ git clone https://github.com/spring-guides/gs-rest-service.git

  3. 開啟Intellij Idea,並匯入Demo工程

    在這裡插入圖片描述

    並直接使用maven的pom.xml匯入
    在這裡插入圖片描述

  4. 建立自己新的工程時,只需將Maven檔案Copy過去,並使用Maven匯入既可

  5. 建立一個簡單的web應用

    可以從Demo裡找到檔案 src/main/java/hello/HelloController.java

package hello;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }
}

該類被標記為@RestController,這意味著Spring MVC可以使用它來處理Web請求。@RequestMapping對映/到index()方法。從瀏覽器呼叫或在命令列上使用curl時,該方法返回純文字。這是因為@RestController組合@Controller和@ResponseBody兩個註釋會導致Web請求返回資料而不是檢視。

src/main/java/hello/Application.java

package hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
 public static void main(String[] args) {
     SpringApplication.run(Application.class, args);
 }
 @Bean
 public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
     return args -> {
         System.out.println("Let's inspect the beans provided by Spring Boot:");
         String[] beanNames = ctx.getBeanDefinitionNames();
         Arrays.sort(beanNames);
         for (String beanName : beanNames) {
             System.out.println(beanName);
         }
     };
 }
}

@SpringBootApplication 是一個便利註釋,添加了以下所有內容:

@Configuration 標記該類作為應用程式上下文的bean定義的源。

@EnableAutoConfiguration 告訴Spring Boot開始根據類路徑設定,其他bean和各種屬性設定新增bean。

通常你會新增@EnableWebMvc一個Spring MVC應用程式,但Spring Boot會在類路徑上看到spring-webmvc時自動新增它。這會將應用程式標記為Web應用程式並激活關鍵行為,例如設定a DispatcherServlet。

@ComponentScan告訴Spring在包中尋找其他元件,配置和服務hello,允許它找到控制器。

該main()方法使用Spring Boot的SpringApplication.run()方法來啟動應用程式。您是否注意到沒有一行XML?也沒有web.xml檔案。此Web應用程式是100%純Java,您無需處理配置任何管道或基礎結構。

還有一個CommandLineRunner標記為a 的方法@Bean,它在啟動時執行。它檢索由您的應用程式建立或由於Spring Boot自動新增的所有bean。它對它們進行分類並打印出來。

  1. Maven 打包

  2. 執行Jar java -jar target/gs-spring-boot-0.1.0.jar

  3. 可以通過localhost:8080正常訪問

在這裡插入圖片描述