Skip to lesson

Component scanning

A class can have the right annotation and still never become a bean, and nothing in the code says why. In a growing project, the package a class lives in decides whether Spring finds it.

Scanning starts at the main class's package

Component scanning is Spring's search for classes marked @Component, @Service, @Repository, @Controller, @RestController or @Configuration. It starts in the package of the @SpringBootApplication class and goes into every sub-package.

Which packages the scan covers when the main class is in com.shoplite.lab, and the beans it finds in boot-lab.

Java
// main class in com.shoplite.lab   → the scan covers:// com.shoplite.lab                  yes (same package)// com.shoplite.lab.product          yes (sub-package)// com.shoplite.lab.order.mail       yes (any depth)// com.shoplite.tools                no  (sibling)// com.shoplite                      no  (parent)
The scan starts at the package of the main class, here com.shoplite.lab, and covers it and every package below it. com.shoplite.lab.product and com.shoplite.lab.order.mail are scanned. The parent com.shoplite and the sibling com.shoplite.tools are not scanned, so a component in them is never found.

Example 1 · BootLabApplication.java, ProductCatalog.java, OrderDesk.java

Runs in: the boot-lab practice project (Spring Boot 4.1)

BootLabApplication.javaJava
// src/main/java/com/shoplite/lab/BootLabApplication.javapackage com.shoplite.lab;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplicationpublic class BootLabApplication {
    public static void main(String[] args) {        ConfigurableApplicationContext context = SpringApplication.run(BootLabApplication.class, args);
        System.out.println("Our beans:");        Arrays.stream(context.getBeanDefinitionNames())                .filter(name -> context.getType(name).getName().startsWith("com.shoplite"))                .sorted()                .forEach(name -> System.out.println("  " + name + " -> " + context.getType(name).getName()));    }}
// src/main/java/com/shoplite/lab/product/ProductCatalog.javapackage com.shoplite.lab.product;
import java.math.BigDecimal;import java.util.Map;
import org.springframework.stereotype.Service;
@Servicepublic class ProductCatalog {
    private final Map<String, BigDecimal> prices = Map.of(            "A4 notebook", new BigDecimal("45.00"),            "Gel pen pack", new BigDecimal("120.00"));
    public BigDecimal priceOf(String product) {        return prices.get(product);    }}
// src/main/java/com/shoplite/lab/order/OrderDesk.javapackage com.shoplite.lab.order;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
import com.shoplite.lab.product.ProductCatalog;
@Servicepublic class OrderDesk {
    private final ProductCatalog catalog;
    public OrderDesk(ProductCatalog catalog) {        this.catalog = catalog;    }
    public BigDecimal total(String product, int quantity) {        return catalog.priceOf(product).multiply(BigDecimal.valueOf(quantity));    }}
Output
Our beans:
  bootLabApplication -> com.shoplite.lab.BootLabApplication
  orderDesk -> com.shoplite.lab.order.OrderDesk
  productCatalog -> com.shoplite.lab.product.ProductCatalog

What this code does

  • The main class is in com.shoplite.lab. ProductCatalog is in com.shoplite.lab.product and OrderDesk in com.shoplite.lab.order, both below it, so the scan found both without any extra setting.
  • main lists only the beans whose class name starts with com.shoplite, so Boot's own beans stay out of the list. The main class is a bean too, because @SpringBootApplication includes @Configuration.
  • OrderDesk asks for ProductCatalog in its constructor and Spring passes the scanned bean in.

Nothing outside that tree is searched. That keeps start-up fast and stops Spring from picking up classes from libraries by accident.

For Examples 1 to 5, boot-lab keeps the two quiet lines from the last lesson (spring.main.banner-mode=off and logging.level.root=warn), so only the program's own output shows.

A bean in a sibling package is never found

A sibling package shares a parent with the main class's package but is not inside it, such as com.shoplite.tools next to com.shoplite.lab. A @Component there is ignored, even though the code compiles and the annotation is correct.

SmsSender has @Component but lives in com.shoplite.tools; OrderDesk needs it, and startup fails.

Example 2 · SmsSender.java (sibling package), OrderDesk.java

Runs in: the boot-lab practice project (Spring Boot 4.1)

SmsSender.javaJava
// src/main/java/com/shoplite/tools/SmsSender.javapackage com.shoplite.tools;
import org.springframework.stereotype.Component;
@Componentpublic class SmsSender {
    public void send(String phone, String text) {        System.out.println("SMS to " + phone + ": " + text);    }}
// src/main/java/com/shoplite/lab/order/OrderDesk.javapackage com.shoplite.lab.order;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
import com.shoplite.lab.product.ProductCatalog;import com.shoplite.tools.SmsSender;
@Servicepublic class OrderDesk {
    private final ProductCatalog catalog;    private final SmsSender smsSender;
    public OrderDesk(ProductCatalog catalog, SmsSender smsSender) {        this.catalog = catalog;        this.smsSender = smsSender;    }
    public BigDecimal placeOrder(String phone, String product, int quantity) {        BigDecimal total = catalog.priceOf(product).multiply(BigDecimal.valueOf(quantity));        smsSender.send(phone, "Order placed: " + quantity + " x " + product + ", Rs " + total);        return total;    }}
Sample output
2026-10-16T10:33:10.129+05:30  WARN 25360 --- [boot-lab] [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderDesk' ...
2026-10-16T10:33:10.381+05:30 ERROR 25360 --- [boot-lab] [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in com.shoplite.lab.order.OrderDesk required a bean of type 'com.shoplite.tools.SmsSender' that could not be found.


Action:

Consider defining a bean of type 'com.shoplite.tools.SmsSender' in your configuration.

What this code does

  • SmsSender has @Component, but it lives in com.shoplite.tools. That package is a sibling of com.shoplite.lab, not a child, so the scan never looks there and no SmsSender bean exists.
  • The report names the class that needed it (OrderDesk), which constructor parameter (parameter 1, counting from 0) and the missing type with its full package. The package is the clue.
  • The Action says "consider defining a bean", which is the same text you get when @Component is missing. Check the annotation first, then the package.

The symptom depends on who needs the class. If another bean asks for it in its constructor, startup fails with "required a bean of type ... that could not be found". If nobody asks, nothing fails: a controller there just never answers, and you get 404s.

A sibling package usually appears when a class is created with the IDE's "New Package" in the wrong place, or code is copied from another project with a different root package.

Fix the error

Pick the package line Spring can find

Read the real startup error, then pick the line that fixes it.

Round 1 of 2

The main class is in com.shoplite.lab. Make SmsSender scannable.

package com.shoplite.tools;
import org.springframework.stereotype.Component;
@Component
public class SmsSender {
}

Error

Parameter 1 of constructor in com.shoplite.lab.order.OrderDesk required a bean of type
'com.shoplite.tools.SmsSender' that could not be found.
Interview angle: "My @Component is not picked up. Why?" Three usual causes: no annotation, a package outside the main class's tree, or a conditional/profile that switches it off.

scanBasePackages, and why moving the main class is usually better

scanBasePackages is an attribute of @SpringBootApplication that sets where scanning starts. It takes one or more package names, and once you set it, the main class's own package is scanned only if you list it too.

Three versions of the main class: scanBasePackages with both packages, with only the new one, and the main class moved up.

Example 3 · Fix 1: scanBasePackages lists both packages

Runs in: the boot-lab practice project (Spring Boot 4.1)

BootLabApplication.javaJava
// src/main/java/com/shoplite/lab/BootLabApplication.java (only the annotation changes)@SpringBootApplication(scanBasePackages = {"com.shoplite.lab", "com.shoplite.tools"})public class BootLabApplication {    // main as in Example 1}
Output
Our beans:
  bootLabApplication -> com.shoplite.lab.BootLabApplication
  orderDesk -> com.shoplite.lab.order.OrderDesk
  productCatalog -> com.shoplite.lab.product.ProductCatalog
  smsSender -> com.shoplite.tools.SmsSender

What this code does

  • scanBasePackages replaces the default starting point with the packages you list, and each is scanned with all its sub-packages. Now smsSender is found and the app starts.
  • Both packages are listed. The default (the main class's package) is no longer added for you once you set the attribute, which leads to the trap in Example 4.

Example 4 · The trap: listing only the new package

Runs in: the boot-lab practice project (Spring Boot 4.1)

BootLabApplication.javaJava
@SpringBootApplication(scanBasePackages = "com.shoplite.tools")public class BootLabApplication {    // main as in Example 1}
Output
Our beans:
  bootLabApplication -> com.shoplite.lab.BootLabApplication
  smsSender -> com.shoplite.tools.SmsSender

What this code does

  • Only com.shoplite.tools is scanned now, so orderDesk and productCatalog disappeared, with no error. The app starts happily without them.
  • In a web app this shows up later as a 404 for every endpoint whose controller was not scanned. A silent missing bean is harder to find than a startup failure.
  • bootLabApplication is still listed because the main class is passed to SpringApplication.run directly; it is not found by scanning.

Example 5 · Fix 2 (better): move the main class up to com.shoplite

Runs in: the boot-lab practice project (Spring Boot 4.1)

BootLabApplication.javaJava
// src/main/java/com/shoplite/BootLabApplication.java   (moved up one package)package com.shoplite;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;
import com.shoplite.lab.order.OrderDesk;
@SpringBootApplicationpublic class BootLabApplication {
    public static void main(String[] args) {        ConfigurableApplicationContext context = SpringApplication.run(BootLabApplication.class, args);
        System.out.println("Our beans:");        Arrays.stream(context.getBeanDefinitionNames())                .filter(name -> context.getType(name).getName().startsWith("com.shoplite"))                .sorted()                .forEach(name -> System.out.println("  " + name + " -> " + context.getType(name).getName()));
        OrderDesk desk = context.getBean(OrderDesk.class);        desk.placeOrder("98450 12345", "Gel pen pack", 2);    }}
Output
Our beans:
  bootLabApplication -> com.shoplite.BootLabApplication
  orderDesk -> com.shoplite.lab.order.OrderDesk
  productCatalog -> com.shoplite.lab.product.ProductCatalog
  smsSender -> com.shoplite.tools.SmsSender
SMS to 98450 12345: Order placed: 2 x Gel pen pack, Rs 240.00

What this code does

  • The main class now sits in com.shoplite, the parent of both lab and tools. Plain @SpringBootApplication with no attributes finds all four beans.
  • In IntelliJ IDEA, drag the class to the parent package (Refactor → Move) so the package line and imports update. In VS Code, move the file and fix the package line; Maven finds the new main class by itself.
  • The last line proves the wiring: OrderDesk got both the catalog and the SMS sender.

scanBasePackages works, but it is a list someone must keep up to date, and a wrong list fails silently (Example 4). The better fix is structural: put the main class in the root package (com.shoplite) and every other package below it. Then the default needs no settings at all.

Keep scanBasePackages for the rare case where you cannot move code, such as a shared company library in another root package. Even then, list the main class's package as well.

How package by feature fits scanning

Package by feature means one package per business feature, such as com.shoplite.product, .category, .customer and .order, plus .common for shared code. Each package holds that feature's controller, service, repository and DTOs.

ShopLite's main class sits in the root package, with every feature below it and found by the scan.

Java
// shoplite-api: the main class is in the root, every feature below it// com.shoplite.ShopliteApiApplication          main class, scan starts here// com.shoplite.common.ApiInfoController        found// com.shoplite.common.config.ClockConfig       found// com.shoplite.order.CartPricingService        found// com.shoplite.product / category / customer   found as soon as classes are added

Package by feature fits scanning naturally. ShopliteApiApplication sits in com.shoplite, every feature is a sub-package, and a new feature (say com.shoplite.review) is scanned the moment you create it. No setting changes as the app grows.

The one rule to keep: never create a package beside com.shoplite, such as com.shopliteadmin or com.example. The Layered Architecture module compares this layout with package by layer.

Startup cost of scanning and keeping the root package tidy

A main class with no package line, started with logging at INFO.

Example 6 · A main class with no package at all

Runs in: the boot-lab practice project, logging at INFO

BootLabApplication.javaJava
// src/main/java/BootLabApplication.java   (no package line)import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class BootLabApplication {
    public static void main(String[] args) {        SpringApplication.run(BootLabApplication.class, args);    }}
Sample output (trimmed with ...)
2026-10-16T10:40:18.884+05:30  INFO 26332 --- [boot-lab] [           main] BootLabApplication                       : Starting BootLabApplication using Java 21.0.7 with PID 26332 (...)
2026-10-16T10:40:18.898+05:30  INFO 26332 --- [boot-lab] [           main] BootLabApplication                       : No active profile set, falling back to 1 default profile: "default"
2026-10-16T10:40:19.161+05:30  WARN 26332 --- [boot-lab] [           main] ionWarningsApplicationContextInitializer :

** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.


2026-10-16T10:40:24.073+05:30  WARN 26332 --- [boot-lab] [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': ...
...
2026-10-16T10:40:24.126+05:30 ERROR 26332 --- [boot-lab] [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': org/aspectj/lang/annotation/Pointcut
...
Caused by: java.lang.NoClassDefFoundError: org/aspectj/lang/annotation/Pointcut
...
Caused by: java.lang.ClassNotFoundException: org.aspectj.lang.annotation.Pointcut
...

What this code does

  • With no package line the class is in the default package, so the scan starts at the very top and reads every class in every jar, Spring's own included.
  • Boot warns at once, and then the start takes seconds longer and fails: the scan picked up an internal Spring configuration class that needs AspectJ, a library this app does not have.
  • The fix is always the same: give the main class a real package (com.shoplite) and keep your code below it.

Scanning cost is the time Spring spends reading class files to find annotated ones. It grows with the number of classes under the starting package, so the start package should hold your code and nothing else.

For ShopLite's size the cost is a fraction of a second. It becomes a real problem only when the start package is too wide: com would scan every library whose package starts with com, and the default package (no package line) scans everything. Keep the root package tidy: only the main class directly in com.shoplite, features in sub-packages, no test or experiment classes left in src/main/java, and no copied classes with their own unrelated packages.

Next step

Check your understanding

10 quick questions