SpringBoot将Controller移至com.example.controllers报WhiteLabel Error的配置方案
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

