How to Organize Spring Boot Projects for Seamless Component Scanning
Spring Boot imposes no strict project layout, but adopting a recommended package structure—placing the main application class in a root package and organizing domain, service, and web layers under it—prevents configuration pitfalls and ensures automatic component scanning, while alternative scanning methods like @ComponentScan and @Bean can handle non‑standard layouts.
Typical Example
Spring Boot does not impose a specific project layout, but following a recommended package structure helps avoid configuration pitfalls, especially with Spring's component scanning.
com
+-example
+-myproject
+-Application.java
|
+-domain
+-Customer.java
+-CustomerRepository.java
|
+-service
+-CustomerService.java
|
+-web
+-CustomerController.javaThe root package (e.g., com.example.myproject) contains all other packages.
The main application class resides in the root package, allowing Spring Boot to automatically scan it and its sub‑packages.
If classes are placed outside the root package, they will not be discovered by default.
Initializing Non‑Typical Structures
When you must load beans from packages outside the root package, you can explicitly specify the packages to scan.
Method 1 – @ComponentScan
@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class Bootstrap {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
}This directly tells Spring which packages to scan, but the conventional structure is still recommended.
Method 2 – @Bean
@SpringBootApplication
public class Bootstrap {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
@Bean
public CustomerController customerController() {
return new CustomerController();
}
}Using @Bean to create beans manually is less common in typical business development and is more suitable for framework extensions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
