spring boot 扫描不到自定义Controller

在 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(</span>"/"<span style="color: rgba(0, 0, 0, 1)">)
@ResponseBody
String home() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> "Hello World!"<span style="color: rgba(0, 0, 0, 1)">;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span> main(String[] args) <span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> Exception {
    SpringApplication.run(SampleController.</span><span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">, 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