Spring Framework - What Is Component Scan?


Spring framework identifies the beans and their dependencies, creates the beans and injects the dependencies into beans. How does the Spring Framework know where to search for beans and dependencies? How does Spring Boot make component scan easier?

You will learn

  • Why do we need Component Scan in Spring?
  • How can you configure a Component Scan in Spring with XML and Java Annotation based configuration?
  • How does Spring Boot provide an automatic Component Scan?
  • How do you solve problems with Component Scan?

In this article, we understand a little bit about component scan in the context of the Spring framework. We also see how component scan works with the Spring Boot framework.

Spring Framework

This is the fourth article in a series of articles on Spring Framework:

Functionality Of The Spring Framework?

What is the fundamental functionality of the Spring framework? It is dependency injection.

Spring framework identifies the beans and their dependencies, finds them and injects the dependencies into beans.

Have a look at the following example:


	@Component
	public class ComplexAlgorithmImpl {
		@Autowired
		privare SortAlgorithm sortAlgorithm;
		//...
	}

	public interface SortAlgorithm {
		public int[] sort(int[] numbers);
	}

	@Component
	public class QuickSortAlgorithm implements SortAlgorithm {
		//...
	}

Let’s quickly look at what Spring Framework needs to do get the autowiring working.

Spring framework needs to create instances of ComplexAlgorithmImpl and QuickSortAlgorithm.

Since QuickSortAlgorithm is the only implementation of SortAlgorithm available, it needs to be auto-wired into the sortAlgorithm field of ComplexAlgorithmImpl.

How Does Spring Search For Beans?

Let’s look at a few questions?

  • How does Spring know where to look for the beans?
  • How does it know where it needs to search for classes with annotations such as @Component and @Service?

A typical application could have hundreds of JARS, and as a result, thousands of classes. Therefore, it is not practical for Spring to search in all the classes present in the CLASSPATH.

Enter Component Scan

Clearly, Spring needs to be given inputs to identify the packages of the beans and dependencies. This is where component scan comes into the picture.

You declare a component scan by passing in a list of packages where the scan needs to take place:


	@Configuration
	@ComponentScan(basePackages = {
			"com.in28minutes.spring.example1.businessservice",
			"com.in28minutes.spring.example1.dataservice.stub"})

	class SpringContext {
	}

The packages mentioned above are the locations where the beans and their dependencies are defined. This @ComponentScan gives a clue to the Spring framework on where to search.

Component Scan With XML Configuration

The thing is, component scan an also be done with XML configuration:

image info

For this, use the <context:component-scan> tag, and specify the packages that are the locations.

How does Auto Configuration work with Spring Boot?

Spring Boot tries to automate a lot of stuff. Consider the code example below:


	package com.in28minutes.spring.basics.springin5steps;

	@SpringBootApplication
	public class SpringIn5StepsApplication {
		//...
	}


	package com.in28minutes.spring.basics.springin5steps;
	
	@RunWith(SpringRunner.class)

	@SpringBootTest
	public class SpringIn5StepsApplicationTests {
		//...
	}

As soon as Spring Boot sees the annotation @SpringBootApplication, it does an automatic scan on the current package, which is com.in28minutes.spring.basics.springin5steps.

You don’t need to explicitly define a component scan. If all the components that you need are present in the same package as SpringIn5StepsApplication, you don’t need to explicitly specify component scan.

Troubleshooting Component Scan In Spring Boot

Have a look at the following Spring Boot application:

image info

Since SpringbootIn10StepsApplication has a @SpringBootApplication annotation attached to it, an automatic component scan in the package com.in28minutes.springboot.basics.springbootin10steps, and all its sub-packages.

However, what would happen if you have one of the components defined in a different package, say com.in28mnutes.springboot.somethingelse?

In this case, you need to add that package to the component scan. There are a couple of options available for doing this.

Explicit Component Scan In Spring Boot

There are two ways of doing an explicit component scan:

Scan a parent package

This would scan the entire parent package tree of com.in28minutes.springboot.


	@ComponentScan("com.in28minutes.springboot")
	
	@SpringBootApplication
	public class SpringBootApllicationIn10Steps {
		//...
	}

Define explicit scans

In this case, we explicitly mention a list of specific packages within the tree. Therefore, only those two paths in the package tree will now get scanned.


	@ComponentScan({
		"com.in28minutes.springboot.basics.springbootin10steps",
		"com.in28minutes.springboot.somethingelse"})
	
	@SpringBootApplication
	public class SpringBootApllicationIn10Steps {
		//...
	}

As soon as you explicitly define a component scan, you are taking complete control. The default automatic scan that generally happens with Spring Boot will not longer take place. You need to specify the default package, as well as other packages.

Let’s look at some of the errors related to component scan and how you can solve them.

Typical Errors

When the controllers are not scanned, the URLs would not work. You would observe behaviors like this:

image info

The other kind of error is when Spring does not find the dependencies. A typical error looks like this:

image info

This means Spring expects at least one bean to auto-wire a dependency, but is not able to locate them.

Solving Errors With Component Scan

Here are some of the things to look fo:

  • Make sure that you have the right annotation for the concerned bean - @Controller, @Repository, @Component.
  • Make sure that the package that a component is present in, is part of the component scan.

Do check out our video on the same topic:

image info

Summary

In this article, we talked about component scan in the context of Spring and Spring Boot frameworks.The @ComponentScan annotation is used to specify packages to locate components in Spring. This is automatically done in the default package, in the case of Spring Boot.

Congratulations! You are reading an article from a series of 50+ articles on Spring, Spring Boot , Hibernate, Full Stack, Cloud and Microservices. We also have 20+ projects on our Github repository. For the complete series of 50+ articles and code examples, click here.

Join 300,000 Learners!

Learn Spring Boot in 10 Steps - FREE Course

Next Steps

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Related Posts

Spring Boot Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. This resources will help you learn and gain expertise at Spring Boot.

Spring and Spring Boot Video Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. Here's a list of video tutorials and courses for you

What is an In Memory Database?

In this article, we understand what the term "In-Memory Database" actually means. We see what scenarios they can be used, and why they are important.

What is an Embedded Server?

In this article, we focus in exploring what an embedded server is, and how they help make application deployment simpler.

Java Tools and Frameworks - Introduction To Maven

In this article, we experience a brief introduction to Maven, and will see how it helps in managing your project dependencies.

Five Tools To Learn as a Java Developer

In this article, we introduce you to five great tools that we recommend every Java Developer to learn.

Five Languages To Learn as a Java Programmer

As a programmer, you want to explore new things. Learning a new language gives you a different perspective when solving problems. What are the 5 languages that a Java developer should explore?

Five Great Frameworks To Try for Java Programmers

As a programmer you want to explore new languages and frameworks. What would be the best frameworks to explore in 2019 for Java Programmers?

Unit Testing Best Practices - with Java and Junit Examples

Unit Testing is often underrated. As far as I am concerned, having good unit tests seperates good projects from bad. In this article, let's look at unit testing best practices in depth. We use examples from Java and JUnit to illustrate the concepts. However, the best practices are applicable irrespective of the programming language used.

Programming Basics - Unit Testing - What Is Mocking?

Mocking is an important concept that is made use of, when writing unit tests. In this article, we explore what mocking is all about, and explore some of the popular Java mocking frameworks in use.