Spring Framework - What Is Component Scan?


NEW COURSE RELEASED! - 21 HOURS, 200+ VIDEOS - Master DevOps with Docker, Kubernetes and Azure DevOps


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.

Free Courses - Learn in 10 Steps

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.

Free Courses - Learn in 10 Steps

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.

What to Learn Next?

NEW COURSE RELEASED! - 21 HOURS, 200+ VIDEOS - Master DevOps with Docker, Kubernetes and Azure DevOps


350,000 Learners are learning everyday with our Best Selling Courses : Spring Boot Microservices, Spring, Spring Boot, Web Services, Hibernate, Full Stack React, Full Stack Angular, Python, Spring Interview Guide, Java Interview, Java Functional Programming, AWS, Docker, Kubernetes, PCF, AWS Fargate and Azure


85,000 Subscribers are learning from our Free Videos on YouTube : JSP Servlets, Spring, Spring Boot, Spring MVC, Hibernate, Eclipse, Maven, JUnit, Mockito, Full Stack - React, Full Stack - Angular, Docker, Kubernetes, AWS, AWS Fargate, PCF and Azure


Here are the recommend articles to read next : Spring Interview Questions, Spring Boot Interview Questions, Microservices, Hibernate, Spring Security, REST API with Spring Boot, Full Stack with React, SOAP Web Services, Exception Handling, Embedded Servers, Spring Data Rest, Spring vs Spring MVC vs Spring Boot, Building Web Application and Spring Data JPA. You can checkout all our 100+ articles here - All Articles.


Do not know where to start your learning journey? Check out our amazing learning paths: Learning Path 01 - Spring and Spring Boot Web Applications and API Developer, Learning Path 02 - Full Stack Developer with Spring Boot, React & Angular, Learning Path 03 - Cloud Microservices Developer with Docker and Kubernetes, Learning Path 04 - Learn Cloud with Spring Boot, AWS, Azure and PCF and Learning Path 05 - Learn AWS with Microservices, Docker and Kubernetes


Related Posts

Docker Tutorial for Beginners - with Java and Spring Boot

Learn about Docker - What is Docker? Why Is Docker Popular? How to create Docker Image for a Java Spring Boot App?

Devops Tutorial | DevOps with Docker, Kubernetes and Azure DevOps

What is DevOps? How is it different from Agile? What are the popular DevOps Tools? What is the role of Docker, Kubernetes and Azure DevOps in DevOps. Let's get started with a simple usecase.

Deploy Java Spring Boot Applications to AWS, Azure, GCP with Docker and Kubernetes

In this article, we focus our attention on the cloud. How to learn the cloud and deploy Java Spring Boot Applications to AWS, Azure, GCP with Docker and Kubernetes?

Microservices Architectures - Non Functional Requirements - Performance

In this article, we explore an important non functional requirement called performance.

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.

Microservices with Spring Boot and Java - Part 1 - Getting Started

Let's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. In part 1 of this series, lets get introduced to the concept of microservices and understand how to create great microservices with Spring Boot and Spring Cloud.

20+ Spring Boot Projects with Code Examples

At in28Minutes, we have created more than 20 projects with code examples on Github. We have 50+ articles explaining these projects. These code examples will you learn and gain expertise at Spring Boot.

REST API Best Practices - With Design Examples from Java and Spring Web Services

Designing Great REST API is important to have great microservices. How do you design your REST API? What are the best practices?

Index - 500+ Videos

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