1.照例登陸http://start.spring.io/ ,改個項目名(Artifact),然后下載導入Eclipse

2. 項目結構如下,
在pom中添加web依賴(不添加,就找不到RestController這個注解要導入的包了)
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-web</artifactId> 4 </dependency>
3.編寫2個配置文件,一個是application.properties,如下:
1 server.port=9090 2 server.servlet.context-path=/spring-boot 3 #server.context-path=/helloboot 4 book.author.name=tom
一個是application.yml ,如下
1 book: 2 author: 3 name1: JACKSON
4. 在com.lch.springboot02.domain 包下創建一個AuthorProperties 類,讀取配置文件信息(同時讀取2個配置文件,實際證明,springboot是可以同時讀取兩種格式的配置文件中的配置信息的),使用注解@Value("${配置文件中的屬性名}")來讀取配置文件,並設置對應屬性接收,還需要設置set get方法
1 package com.lch.springboot02.domain; 2 3 import org.springframework.beans.factory.annotation.Value; 4 import org.springframework.stereotype.Component; 5 6 @Component 7 public class AuthorProperties { 8 9 @Value("${book.author.name}") 10 private String authorName; 11 12 @Value("${book.author.name1}") 13 private String authorName1; 14 15 16 public String getAuthorName() { 17 return authorName; 18 } 19 20 public void setAuthorName(String authorName) { 21 this.authorName = authorName; 22 } 23 24 public String getAuthorName1() { 25 return authorName1; 26 } 27 28 public void setAuthorName1(String authorName1) { 29 this.authorName1 = authorName1; 30 } 31 }
5. 在com.lch.springboot02.controller 包下建立contorller類 PropertiesController ,把讀取到的配置信息返回給前台顯示,這里需要注入 AuthorProperties 的實例
1 package com.lch.springboot02.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RestController; 6 7 import com.lch.springboot02.domain.AuthorProperties; 8 9 @RestController // 使用這個注解必須在pom中引入web模塊的依賴! 10 public class PropertiesController { 11 @Autowired 12 AuthorProperties properties; 13 14 @RequestMapping("/hello") 15 public String hello() { 16 return "hello spring-boot"; 17 } 18 19 @RequestMapping("/author") 20 public String author() { 21 return "the author name is: " + properties.getAuthorName() + ", the author name1 is: " + properties.getAuthorName1(); 22 } 23 24 }
6. 啟動應用,訪問:http://localhost:9090/spring-boot/author ,結果如下:

之所以是這個請求路徑,控制台告訴了我們:

在上一個入門例子中,應用默認端口是8080,context path 是空,這里發生了變化,這是因為springboot讀取到了application.properties中配置的端口號和上下文路徑(
server.port=9090 server.servlet.context-path=/spring-boot ),並進行了應用.
注意:spring boot 2.0.0的ContextPath配置有變化: server.servlet.context-path=/XXX ,之前是server.context-path=/xxx
在前端頁面展示的結果中,看到了name1的值也有,說明application.yml配置文件中的信息也讀取到了。
例子下載地址:
https://github.com/liuch0228/springboot.git
