Auto component scan in Spring

Apart from initializing the bean in the Spring container using an XML file or using the @Configuration annotation, we can also initialize the bean using Spring’s auto component scan. How is it in details? I will tell you in this tutorial.

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

Auto component scan in Spring

Next, I will add the Spring dependency to the pom.xml file as follows:

Now, I will add a new class HelloWorld in the package com.huongdanjava.springcomponentscan:

Auto component scan in Spring

with the following content:

To use auto component scan in Spring, there are two steps we need to do:

First of all, we must declare a context:component-scan tag in Spring’s configuration file.

Auto component scan in Spring

In this tag, we have an attribute named base-package. Declaring a package name that contains the object we need to initialize the bean in Spring’s container, into this property, Spring will automatically initialize the bean for us.

In my example, I want Spring to initialize the bean for the HelloWorld object automatically, then I will declare the context:component-scan tag as follows:

The second step, we need to do is to add one of the following annotations to the object that we want Spring to automatically initialize the bean.

The annotation is: @Component, @Repository, @Service and @Controller. Each annotation has the following meanings:

– @Component: for non-database objects, business logic or presentation layer.

– @Repository: Used for objects related to the database layer.

– @Service: for objects related to business logic layer.

– @Controller: for objects related to the presentation layer.

Actually, you can use the above annotation for any object. But to be more precise in terms of semantics for each object, you should use them appropriately.

In our example, the HelloWorld object is not related to the database, business logic, or presentation layer, so we will use the @Component annotation as follows:

OK, that’s it. The id of the bean is the name of the class with the first character in lowercase.

Now let’s try running this example.


Auto component scan in Spring


Auto component scan in Spring
Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
2Tweet about this on Twitter
Share on LinkedIn

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.