1 Springboot入門程式
- 上一篇已經寫了如何建立項目,這一篇寫一下如何寫第一個Controller
- 首先打開自己的Application類,加上如下代碼
@SpringBootApplication
@RestController
public class DemoApplication {
@RequestMapping("hello")
public String hello(){
return "hello1";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 然後run as application
- 在位址欄輸入http://127.0.0.1:8080/hello
- 我們再試試在Controller包下寫一個方法
- 寫上如下代碼
package com.example.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller1 {
@RequestMapping("info1")
public String info(){
return "hello world";
}
}
同樣的run as application卻發現出現404錯誤
這時在啟動類注解上加點東西
@SpringBootApplication(scanBasePackages = "com")
- 再啟動,發現可以啟動并通路info1請求了。
- 我猜想是scanBasePackages =“com”指明可以請求com包下所有請求,如果不加,預設隻有啟動類包下的請求。
熱啟動
- 小夥伴們應該發現,頻繁改動代碼,頻繁runasapplication很麻煩了,springboot這裡支援熱啟動,我們隻需要在pom.xml加入如下配置即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
至此,咱們寫好第一個請求并通路到,本篇嘚瑟完畢,待會再嘚瑟下一篇。