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

SpringBoot将Controller移至com.example.controllers报WhiteLabel Error的配置方案

Fixing Spring Boot WhiteLabel Error When Controller is in a Non-Default Package

This issue happens because Spring Boot's default component scanning only covers the package where your main application class (DemoApplication) resides and its subpackages. Since DemoApplication lives in com.example.demo, moving HomeController to com.example.controllers takes it outside this default scope—so Spring never detects and registers the controller, leading to the WhiteLabel Error Page.

Here are two straightforward solutions to expand the scanning range:

1. Update the @SpringBootApplication annotation

You can explicitly specify the packages to scan using the scanBasePackages attribute directly on @SpringBootApplication:

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.controllers"})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Alternatively, if you prefer type-safe references (to avoid typos in package names), use scanBasePackageClasses to specify classes from the target packages:

@SpringBootApplication(scanBasePackageClasses = {DemoApplication.class, HomeController.class})
public class DemoApplication {
    // Main method remains unchanged
}

2. Add a @ComponentScan annotation

Since @SpringBootApplication already includes @ComponentScan, you can add an explicit @ComponentScan to define the full set of packages to scan:

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.example.demo", "com.example.controllers"})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

⚠️ Important: Be sure to include your original main package (com.example.demo) in the scan list—otherwise Spring won't detect other components in that package either.

Both approaches work by telling Spring to look for components (like @RestController, @Service, @Repository) in the specified packages. After making either change, restart your application and the / endpoint should work as expected.

内容的提问来源于stack exchange,提问作者rdafs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:14:24