Spring Boot之“Hello World”
小弟剛接觸spring boot不久,僅想通過寫網誌的形式來加深記憶和方便以後查閱。如內容有不正確之處,還望各位大佬海量汪涵,並給小弟指出,共同進步。
講到第一個應用程序,首先想到的肯定是“Hello World”。那麼就使用Spring Boot開發一個簡單的“Hello World”Web應用程序,以突顯出一些Spring Boot的主要功能。
1.1創建pom
首先我們需要先創建一個Maven的pom.xml文件,pom.xml用於構建項目所需jar。
<?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> com.demo </groupId>
<artifactId> myproject </artifactId>
<version> 0.0.1-SNAPSHOT </version>
<parent>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-starter-parent</artifactId>
<version> 2.0.0.BUILD-SNAPSHOT </version>
</parent>
<repositories>
<!--指定id爲spring-snapshots的jar正式版本下載地址 -->
<repository>
<id> spring-snapshots </id>
<url> http://repo.spring.io/snapshot </url>
<snapshots><enabled >true</enabled></snapshots>
</repository>
<!--爲產生最終版本,會經過n個milestones來實現 -->
<repository>
<!--除非知道在做什麼,否則不要使用milestones -->
<id> spring-milestones </id>
<url> http://repo.spring.io/milestone </url>
</repository>
</repositories>
<!--指定插件下載的地址 -->
<pluginRepositories>
<pluginRepository>
<id> spring-snapshots </id>
<url> http://repo.spring.io/snapshot </url>
</pluginRepository>
<pluginRepository>
<id> spring-milestones </id>
<url> http://repo.spring.io/milestone </url>
</pluginRepository>
</pluginRepositories>
</project>
1.2添加依賴關係
Spring Boot提供了一些“starters”,可以方便地將jar添加到類路徑中。
繼承spring-boot-starter-parent後,提供了有用的Maven默認值。它還提供了一個 dependency-management 部分,以便可以省略version,統一管理版本號。
<dependencies>
<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-starter-web </artifactId>
</dependency>
</dependencies>
注:spring-boot-starter-web內嵌了一個Tomcat服務器。
1.3編寫Hello World
@RestController
@EnableAutoConfiguration
public class Demo {
@RequestMapping("/")
String hello() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Demo.class, args);
}
}
1.4 @RestController與@Controller
@RestController註解相當於@ResponseBody +@Controller合在一起的作用。
注:只使用@Controller,如需要返回JSON內容到頁面,則需要在對應的方法上加上@ResponseBody註解。
1.5 @RequestMapping
@RequestMapping提供路由信息,告訴Spring任何路徑“/”的Http請求都映射到hello()方法。
1.6 @EnableAutoConfiguration
該註解的字面意思是開啓自動配置,則是在告訴Spring Boot根據添加的jar依賴關係來配置Spring。
1.7 Spring Boot的入口
Spring Boot的入口在main方法中,SpringApplication通過調用委託給Spring Boot的run()方法,從引導應用程序啓動Spring,然後啓動自動配置的Tomcat web服務器。將Demo.class作爲參數傳給run方法來判斷SpringApplication是哪個的組件。
1.8 創建可執行jar
Java不提供任何標準的方式來加載嵌套的jar文件(即jar包含在jar中的jar文件)。
要用使用Spring Boot創建可執行的jar,我們需要添加spring-boot-maven-plugin到我們的 pom.xml:
<build>
<plugins>
<plugin>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-maven-plugin </artifactId>
</plugin>
</plugins>
</build>
1.9 啓動項目
訪問localhost:8080,會得到Hello World。