在SpringBoot,可以定義一個全局配置文件,全局配置文件有兩種形式:
1). application.properties
2).application.yml
二者的后綴名不同,編輯的格式也不同,但都是全局配置文件,二者選其一即可,都可以起到相同的作用
在你的maven工程下的src/main/resources 新建一個文件,以 application.properties為例。
然后編輯以下內容
book.author=Tom
book.name=Spring
然后在src/main/java下新建一個java.class並寫入以下的代碼
1 @EnableAutoConfiguration //根據所依賴的jar包進行自動配置
2 @Controller 3 public class Example { 4
5 @Value("${book.author}") 6 private String author; 7
8 @Value("${book.name}") 9 private String name; 10
11 @RequestMapping("/bookInfo") //映射路由
12 @ResponseBody 13 public String showInfo() 14 { 15 return author+":"+name; 16 } 17 public static void main(String[] args) { 18 // TODO Auto-generated method stub
19 SpringApplication.run(Example.class,args); 20
21 } 22
23 }
保存后構建maven,然后運行該java.class
就可以在相應的地址(http://localhost:8080/bookInfo)獲取對應的屬性。
當然,如果application.properties中的屬性比較少,用上述的方式是可行的,但是如果application.properties中有很多的屬性的時候,每次都要寫一次@Value,是不是過於累贅?
於是有 @ConfigurationProperties實現類型安全的配置(在application.properties的基礎上)。
先看具體的實現,application.properties配置文件的內容和上面的相同
1 @EnableAutoConfiguration // 根據所依賴的jar包進行自動配置
2 @Controller 3 @ConfigurationProperties(prefix = "book") 4 public class Example { 5
6 // @Value("${book.author}")
7 private String author; 8
9 // @Value("${book.name}")
10 private String name; 11
12 public String getAuthor() { 13 return author; 14 } 15
16 public void setAuthor(String author) { 17 this.author = author; 18 } 19
20 public String getName() { 21 return name; 22 } 23
24 public void setName(String name) { 25 this.name = name; 26 } 27
28 @RequestMapping("/bookInfo") // 映射路由
29 @ResponseBody 30 public String showInfo() { 31 return author + ":" + name; 32 } 33
34 public static void main(String[] args) { 35 // TODO Auto-generated method stub
36 SpringApplication.run(Example.class, args); 37
38 } 39
40 }
注意:@ConfigurationProperties(prefix = "book"),寫在獲取成員變量的類前。
然后就是,對於類中的成員變量命名,要是application.properties屬性中除了前綴外的剩余部分,比如我的application.properties中的 book.name,那么想獲取其屬性時,就要定義一個String name,此外,成員變量需要get和set方法。
最后,關於application.properties配置文件中,屬性的命名最好都已相同的前綴開頭(比如上面都是以book開頭)
這樣,就不用每次都寫@Value了
關於 @Controller和@RestController的區別
@RestController,一般是使用在類上的,它表示的意思其實就是結合了@Controller和@ResponseBody兩個注解,@ResponseBody,一般是使用在單獨的方法上的,需要哪個方法返回json數據格式,就在哪個方法上使用,具有針對性。
@RestController注解相當於@ResponseBody + @Controller合在一起的作用。 RestController使用的效果是將方法返回的對象直接在瀏覽器上展示成json格式,而如果單單使用@Controller會報錯,需要ResponseBody配合使用。
1、如果只是使用@RestController注解Controller類,則方法無法返回jsp頁面,配置的視圖解析器InternalResourceViewResolver不起作用,返回的內容就是Return 里的內容。 例如:本來應該到success.jsp頁面的,則其顯示success.
2、如果需要返回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
3、如果需要返回JSON,XML或自定義mediaType內容到頁面,則需要在對應的方法上加上@ResponseBody注解。
或者以下的解釋:
此外,在配置文件中可以配置的屬性請參考:springboot全局配置文件可設置的屬性