spring boot 自定义Controller,不能被扫描

在springboot官网照着给的介绍写了个springboot程序

pom.xml

1
2
3
4
5
6
7
8
9
10
11
<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文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

spring boot 自定义Controller,不能被扫描

但是无论如何也无法扫描到自己定义的Controller(如果用的是idea,能明显看出来,如果扫描到会有spring boot 自定义Controller,不能被扫描的图标)。访问结果结果如下:

spring boot 自定义Controller,不能被扫描

 

郁闷至极,到晚上搜的结果说的是SampleController 方的位置不对,应该让启动类和Controller的包在同一级目录下,然而对我却没有效果。

官方建议application.java放的位置:

spring boot 自定义Controller,不能被扫描

最后尝试了下修改下Application上的注解,我本来复制官方的代码用的是@Controller和@EnableAutoConfiguration,换成了@SpringBootApplication注解,出乎意外的可以扫描到Controller 

spring boot 自定义Controller,不能被扫描

spring boot 自定义Controller,不能被扫描

spring boot 自定义Controller,不能被扫描

 

真郁闷居然是这个原因,官方的文档说得是@Controller和@EnableAutoConfiguration和@SpringBootApplication没有区别的。

被这个问题难倒了一晚上,该跳的坑一个都不能少啊。

 

续写:

又查了下官方的文档终于找到原因了,原因是:

@Controller和@EnableAutoConfiguration 还应该再加上一个注解:@ComponentScan  就可以了。

 

总结:

使用springboot扫描的两种注解配置方式:

1、@Controller

   @EnableAutoConfiguration

  @ComponentScan

2、@SpringBootApplication

@SpringBootApplication注解等价于以默认属性使用@Configuration@EnableAutoConfiguration@ComponentScan

另外application.java也应该按照官方的建议放在root目录下,这样才能扫描到Service和dao,不然还会引起,扫描不到注解的问题。