Video in progress

Junior 🌱 Spring

Which packages does @ComponentScan scan, and what happens if a class is outside the main package?

By default, the package containing @SpringBootApplication and all its subpackages are scanned. Spring doesn't see a @Component class outside it, so it doesn't become a bean.

📖 Answer

@SpringBootApplication contains @ComponentScan, and when no package is given it searches downward from the package where that class sits.

uz.shop                  <- ShopApplication is here
uz.shop.order            <- scanned
uz.shop.payment.service  <- scanned
uz.common.mail           <- NOT scanned

Even if uz.common.mail.MailService has @Service on it, Spring doesn't see it, and the application fails at startup because of whatever injects it.

What you can do:

  • the cleanest fix is to put the main class in the highest common package (uz), or move the code under uz.shop;
  • or list the packages explicitly: @SpringBootApplication(scanBasePackages = {"uz.shop", "uz.common"});
  • if the class is in an external library, use @Import(MailService.class) or a @Bean method.

In practice: don't put the main class in the default (unnamed) package. Spring will try to scan the whole classpath, and startup becomes very slow.