在springboot官網照着給的介紹寫了個springboot程序
pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
java文件
package hello; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.stereotype.*; import org.springframework.web.bind.annotation.*; @Controller @EnableAutoConfiguration public class Application{ @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(SampleController.class, args); } }
然后自己寫了個Controller
但是無論如何也無法掃描到自己定義的Controller(如果用的是idea,能明顯看出來,如果掃描到會有的圖標)。訪問結果結果如下:
報錯的原因是找不到對應的映射路徑,即Controller沒有被掃描到 ,。
郁悶至極,到晚上搜的結果說的是LoginController 方的位置不對,應該讓啟動類和Controller的包在同一級目錄下,然而對我卻沒有效果。
官方建議application.java放的位置:
最后嘗試了下修改下Application上的注解,我本來復制官方的代碼用的是@Controller和@EnableAutoConfiguration,試着換成了@SpringBootApplication注解,出乎意外的可以掃描到Controller
又查了下官方的文檔終於找到原因了,原因是:
如果使用@Controller和@EnableAutoConfiguration 注解還應該再加上一個注解:@ComponentScan 就可以了。@Controller和@EnableAutoConfiguration沒有掃描注解的功能,而@ComponentScan是
springboot專門用來掃描@Component, @Service, @Repository, @Controller等注解的注解
總結:
使用springboot啟動類配置掃描的兩種注解配置方式:
1、@Controller
@EnableAutoConfiguration
@ComponentScan
2、@SpringBootApplication
@SpringBootApplication注解等價於@Configuration, @EnableAutoConfiguration and @ComponentScan
另外application.java(啟動類)也應該按照官方的建議放在root目錄下,這樣才能掃描到Service和dao,不然還會引起,掃描不到注解的問題。
--- 更新日期:2018-10-14 ---
最近用了最新的springboot 2.0.5.RELEASE 版本 多了一種新的掃描注解,新版的springboot application可以放在任意位置,只要加上
@ComponentScan(basePackages = {"com.oskyhang", "com.frames"})
注解就可以,注解指定掃描的包,就可以掃描到,更靈活方便。
PS:如有疑問或錯誤,歡迎指教。3Q