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.

Programmer DD
Programmer DD
Programmer DD
How to Organize Spring Boot Projects for Seamless Component Scanning

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.java

The 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaSpring Bootcomponent scanning
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.