spring Boot无法扫描自定义controller

Spring Boot启动类与自定义Controller不在同一级目录导致路由找不到。官方建议将application.java位置调整,但更推荐使用@SpringBootApplication结合@ComponentScan指定自定义controller所在包。@RestController注解用于标记controller。通过检查组件扫描并访问URL确认问题已解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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  可以看到成功了!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值