@ComponentScan example in spring boot

In this article, we will see @ComponentScan example in spring boot.

  • @ComponentScan introduced in Spring 3.1, available in org.springframework.context.annotation package.
  • In XML based configuration we suppose to write <context:component-scan>, @ComponentScan annotation behaves same way.
  • Using this annotation we tell to Spring scan these packages and available classes.
  • Generally, we use this annotation with the configuration class.

Let’s see an example, how to use this annotation and what will problem without it.

open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)click on next.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’click on next. Fill all details(GroupId – ComponentScanExample, ArtifactId – ComponentScanExample and name – ComponentScanExample) and click on finish.




Define classes.






Run the SpringMain.java class and test from the postman.


We are using @ComponentScan annotation with SpringMain.java class. Although in real time scenario generally, we write with configuration class. So what will happen if we remove this annotation attribute? Something like below –

public class SpringMain {
public static void main(final String[] args) {
SpringApplication.run(SpringMain.class, args);


While deployment we will not have any issue. But if you try to hit same URI from the postman we will get 404 found.

@ComponentScan example in spring boot

So what’s going on? Since we have defined our controller classes and pojo(Book.java) in different packages Spring is not able to identify those classes. If we have a different package structure for the controller, service, and repository then we must need to tell spring explicitly using @ComponentScan annotation. That’s all about @ComponentScan example in spring boot.


You may like.

@ComponentScan annotation docs.