最近要做一個客戶端的活,準備使用輕量級的Spring Boot來完成,記錄整個Spring Boot學習過程
-
需要準備的內容
- JDK 1.8 or later
- 一個IDE,我習慣於使用Intellij Idea
- Maven
-
克隆Github上的Demo
$ git clone https://github.com/spring-guides/gs-rest-service.git
-
打開Intellij Idea,並導入Demo工程
並直接使用maven的pom.xml導入
-
創建自己新的工程時,只需將Maven文件Copy過去,並使用Maven導入既可
-
創建一個簡單的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。它對它們進行分類並打印出來。
-
Maven 打包
-
執行Jar
java -jar target/gs-spring-boot-0.1.0.jar
-
可以通過
localhost:8080
正常訪問