主要的話說在前面:在啟動日志中沒有看到Controller對應的URL被映射,那么請檢查你的Controller是否被Spring管理了。此次踩坑就是忘了SpringBoot在沒配置@ComponentScan的情況下,默認只掃描和主類處於同包下的Class。
一個很簡單的Spring Boot的Hello World,主要是根據請求返回一個字符串。如下是項目結構:

主類Application.java:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Controller類HelloController:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping(value="/hello", method = RequestMethod.GET)
public String hello() {
return "Hello, Spring Boot";
}
}
配置文件application.properties:
server.port=8082 server.servlet.context-path=/springboot
啟動日志中沒有看到請求"/hello"被映射:

因為Application和HelloController沒有在同一個包下,且在Application中沒有加上@ComponentScan指定掃描路徑,所以HelloController並沒有被納入Spring管理,那么在啟動日志中肯定就見不到HelloController的URL的Mapping。
解決辦法:
1. 將Application和HelloController放到同一個包下
2.在Application商加上@ComponentScan,指定需要掃描的路徑。這里我們將采用這種方法。
加上@ComponentScan的Application:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.andywooh.springboot")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
啟動日志終於看到"/hello":

