🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Prerequisites
- JDK 17 or later
- Maven or Gradle
- IDE (IntelliJ IDEA, Eclipse, etc.)
What is Component Scanning?
Component scanning is the process of automatically discovering and registering beans in the Spring application context. It is typically enabled through annotations such as @Component, @Service, @Repository, and @Controller.
Step-by-Step Guide
Step 1: Set Up a Spring Boot Project
Use Spring Initializr to create a new project with the following configuration:
- Project: Maven Project
- Language: Java
- Spring Boot: 3.2.x
- Dependencies: Spring Web
Download and unzip the project, then open it in your IDE.
Step 2: Create Components
Create different components in various packages to demonstrate component scanning.
2.1 Create a Service Component
Create a class named MyService in the com.example.demo.service package.
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String serve() {
return "Service is working";
}
}
Explanation:
@Service: Marks the class as a service component, making it eligible for component scanning and automatic registration.
2.2 Create a Repository Component
Create a class named MyRepository in the com.example.demo.repository package.
package com.example.demo.repository;
import org.springframework.stereotype.Repository;
@Repository
public class MyRepository {
public String fetch() {
return "Repository is working";
}
}
Explanation:
@Repository: Marks the class as a repository component, making it eligible for component scanning and automatic registration.
2.3 Create a Controller Component
Create a class named MyController in the com.example.demo.controller package.
package com.example.demo.controller;
import com.example.demo.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/test")
public String test() {
return myService.serve();
}
}
Explanation:
@RestController: Marks the class as a REST controller component, making it eligible for component scanning and automatic registration.@Autowired: Automatically injects theMyServicebean into the controller.
Step 3: Configure Component Scanning
3.1 Default Component Scanning
By default, Spring Boot scans for components in the package where the @SpringBootApplication annotation is located and all its sub-packages. Therefore, if your DemoApplication class is located in the com.example.demo package, it will automatically scan for components in the com.example.demo package and its sub-packages.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Explanation:
@SpringBootApplication: A convenience annotation that combines@Configuration,@EnableAutoConfiguration, and@ComponentScan.
3.2 Customizing Component Scanning
If your components are located outside the default package structure, you can customize the component scanning using the @ComponentScan annotation.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.demo.service", "com.example.demo.repository", "com.example.demo.controller"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Explanation:
@ComponentScan(basePackages = {...}): Specifies the packages to scan for components.
Step 4: Running and Testing the Application
4.1 Run the Application
Run the Spring Boot application using your IDE or the command line:
./mvnw spring-boot:run
4.2 Test the Component Scanning
Open a web browser or use a tool like Postman to send a GET request to http://localhost:8080/test. You should see the message "Service is working" returned from the MyService component, indicating that component scanning and dependency injection are working correctly.
Additional Configurations
Excluding Specific Beans
You can exclude specific beans from being scanned and registered using the @ComponentScan.Filter annotation.
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.demo"},
excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MyRepository.class))
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Explanation:
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MyRepository.class): Excludes theMyRepositoryclass from component scanning.
Using @Component for Custom Components
You can create custom components using the @Component annotation.
package com.example.demo.custom;
import org.springframework.stereotype.Component;
@Component
public class MyCustomComponent {
public String custom() {
return "Custom component is working";
}
}
Explanation:
@Component: Marks the class as a generic component, making it eligible for component scanning and automatic registration.
Conclusion
In this comprehensive guide, you have learned how to use component scanning in Spring Boot. We covered:
- Setting up a Spring Boot project.
- Creating different components (
@Service,@Repository,@RestController). - Configuring default and customized component scanning.
- Running and testing the application.
By following these steps, you can effectively use component scanning to simplify the configuration and development process in your Spring Boot applications.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment