You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.0.3中Controller Bean未创建,API无法暴露求助

解决Spring Boot Controller未被实例化、接口无法访问的问题

针对你遇到的TestController未被创建为Bean、/test接口无法访问的问题,可以按以下步骤排查解决:

  • 确认组件扫描范围:
    虽然@SpringBootApplication默认会扫描主类所在包(com.example.demo)及其子包,但显式指定扫描包可以避免潜在的扫描异常。修改DemoApplication类的注解:

    @SpringBootApplication(scanBasePackages = "com.example.demo")
    
  • 重新编译项目:
    执行Gradle命令清理并重新编译,确保Controller类被正确编译到输出目录:

    ./gradlew clean build
    

    编译完成后再启动应用,检查Actuator的/beans和/mappings接口。

  • 清理IDE缓存:
    若使用IDEA或Eclipse等IDE,缓存问题可能导致类未被正确加载。以IDEA为例,执行File -> Invalidate Caches... -> Invalidate and Restart,重启后重新运行项目。

  • 检查启动日志:
    查看应用启动日志,搜索TestController或com.example.demo.controller关键词,确认是否有组件扫描相关的报错或跳过信息。正常情况下,Spring Boot会打印扫描到的Bean信息,若没有相关日志,说明扫描逻辑确实未覆盖到该类。


你的代码参考:

Controller类

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/test")
    public String test(){
        return "test";
    }
}

主应用类

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

配置文件(application.properties)

server.port=8081
management.endpoints.web.base-path=/
management.endpoints.web.exposure.include=*

构建脚本(build.gradle)

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.0.3'
    id 'io.spring.dependency-management' version '1.1.0'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

内容的提问来源于stack exchange,提问作者B Bharat Bhusan Subudhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 15:25:25