Spring Boot自动组件扫描未检测到RestController,需手动添加@ComponentScan?
你的RestController未被Spring Boot自动扫描到,核心原因是默认组件扫描范围的限制。
默认扫描规则
@SpringBootApplication注解已经包含了@ComponentScan功能,它默认仅扫描主启动类(DemoApplication)所在包及其所有子包内的组件(包括标注了@RestController、@Service、@Component的类)。
问题根源
你的RegistryController所在的restController包,不在主类的默认扫描范围内——比如主类位于com.example.demo这类根包下,而Controller直接在restController根包中,或者两者是同级包而非父子包,导致Spring Boot启动时无法发现这个Controller。
两种解决方案
方案1:调整包结构(推荐)
将RegistryController移动到主类所在包的子包中,比如主类在com.example.demo,就把Controller放到com.example.demo.controller或com.example.demo.restcontroller子包下,无需额外配置,Spring Boot会自动扫描到。
方案2:指定扫描包路径
若不想调整包结构,可在主类上明确指定需要扫描的包:
@SpringBootApplication(scanBasePackages = {"你的主类所在包路径", "restController"}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
或者单独使用@ComponentScan指定多个包:
@SpringBootApplication @ComponentScan({"你的主类所在包路径", "restController"}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
这样既覆盖主类所在包的默认扫描,又包含了Controller所在的包。
小提示
Java包名规范为全小写,建议将restController改为restcontroller,避免驼峰格式,虽然不影响功能,但更符合编码规范。
内容的提问来源于stack exchange,提问作者salmen MC

