Auto component scan in Spring using @ComponentScan annotation

In the previous post, I showed you how to auto component scan using the configuration in the XML file. In this tutorial, I show you how to do this with Java code using the @ComponentScan annotation.

First, I will create a new Maven project as an example:

I will use Java 17 for this example application:

Spring dependency is as follows:

Now, I will add a HelloWorld class declared with the @Component annotation as follows:

Next, I will create a new class to configure the application:

As you can see, I have annotated this ApplicationConfiguration class with the @ComponentScan annotation, the purpose of the @ComponentScan annotation is to automatically scan and initialize the beans in the Spring container for the annotated classes with the @Component, @Repository, @Service, and @Controller annotation.

The attributes of the @ComponentScan annotation are as follows:

The @ComponentScan annotation allows us to declare packages that Spring can scan and initialize beans. By default, if we don’t declare attribute basePackages, then Spring will get the package containing the class that we declare this @ComponentScan annotation, to scan. You can declare the basePackages attribute if you want, for example like this:

The @ComponentScan annotation also allows us to declare packages of the classes they belong to for scanning, using the basePackageClasses attribute.

We can also define how the bean names are generated (attribute nameGenerator), a filter that allows Spring to create beans for some classes (attribute includeFilters), disallow the creation of beans for some classes (attribute excludeFilters), and create beans immediately or only when that class is used to (attribute lazyInit), … Depending on your needs, please configure this annotation correctly!

In my example, the ApplicationConfiguration class is in the same package as the HelloWorld class, so I don’t need to declare anymore.

The main class to run this application has the following content:

The result when running the application is still the same as in the previous tutorial:

Add Comment