spring boot 自定義controller路由找不到,原因是啓動類和自定義的Controller包不在同一級目錄下。
官方建議application.java放的位置:
解決的辦法:
1、把自建的controller類放到啓動類同一級目錄下(不建議這樣做)並且使用@SpringBootApplication註解,而且自定義controller需要使用@RestController註解。
2、使用@SpringBootApplication + @ComponentScan("自定義controller所在的包")
把啓動類@RestController @EnableAutoConfiguration註解改成@SpringBootApplication
@SpringBootApplication註解等價於以默認屬性使用@Configuration,@EnableAutoConfiguration和@ComponentScan
@ComponentScan是springboot專門用來掃描@Component, @Service, @Repository, @Controller等註解的註解
但是加上去的時候還要加上具體掃描的區域,我試過把註解裏的掃描區域去掉,這樣依舊無法掃描到自定義的controller。
自定義controller使用註解@RestController。
使用上訴兩種方式皆可,建議使用第二種方式。
通過界面上的“C”可以看出自定義controller已經背掃描到了。
訪問url:http://localhost:8080/main/index 可以看到成功了!