spring boot 扫描不到自定义Controller

spring boot 扫描不到自定义Controller
在springboot官网照着给的介绍写了个springboot程序

pom.xml

复制代码

org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE



org.springframework.boot
spring-boot-starter-web


复制代码

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值