ReviseAlgo Logo

Spring Fundamentals

Component Scanning and Stereotype Annotations (@Component, @Service, @Repository)

How Spring performs classpath scanning and filters component configurations.

Interview: Very common to be asked about the differences between @Component, @Service, @Repository, @Controller, and how component scanning can be customized or configured.

Last Updated: June 15, 2026 12 min read

Introduction

Component scanning is the mechanism by which Spring scans classes in your classpath, identifies specific stereotype annotations, parses them, and automatically registers them as beans inside the container. This eliminates the need to manually declare beans in XML configurations or write custom Java configuration classes with @Bean declarations.

Why It Matters

If Spring's classpath scanning is misconfigured, your components will not be registered, leading to the infamous NoSuchBeanDefinitionException at startup. Correctly placing classes within package scan folders, understanding how stereotyping works, and using specialized annotations like @Service and @Repository ensures clean layers and activates database-specific exception processing.

Real-World Analogy

Think of component scanning like a **corporate headhunter scanning resumes**:

  • The Scanning Zone (basePackages): The recruiter only looks at candidates located in a specific city/region (the scanned packages).
  • The Keywords (Stereotype Annotations): The recruiter searches for candidate resumes containing specific job badges: "Developer" (@Component), "Accountant" (@Service), or "Database Admin" (@Repository).
  • The Registry: Anyone found with these certifications is automatically added to the company roster (Registered as a Spring Bean). If a candidate works outside the scanned region, they are ignored entirely.

Stereotype Hierarchy

Spring's core annotations inherit from @Component, establishing semantic specializations for each layer of your application:

Annotation Layer Specialized Behavior
@Component Generic Declares the class as a general-purpose Spring-managed component.
@Service Business Logic Adds semantic meaning denoting business service layers (no additional technical behavior).
@Repository Data Access Enables automatic Exception Translation, converting database exceptions into Spring's DataAccessException.
@Controller / @RestController Presentation Maps incoming web HTTP requests directly to handler methods, with @RestController serializing response payloads to JSON/XML.

Practical Example

Here is how to configure a Spring Boot application's base scan packages and define stereotype-layered beans:

Quick Quiz

Q1: Which annotation acts as the parent meta-annotation for all Spring stereotypes like @Service and @Repository?

A) @Bean

B) @Component

C) @Autowired

D) @Configuration

Answer: B — @Component is the root stereotype annotation; @Service, @Repository, and @Controller are all internally annotated with @Component.

Q2: What is the default component scanning behavior if you do not specify package locations on @SpringBootApplication?

A) Spring scans the entire filesystem.

B) Spring does not scan any packages (you must define every bean manually).

C) Spring scans the package containing the main application class and all of its sub-packages.

D) Spring only scans java.lang packages.

Answer: C — Modern Spring Boot projects use implicit base package scanning based on the physical folder structure starting at your main bootstrap class's package.

Scenario-Based Challenge

Production Scenario:

You are adding a shared library containing general utility beans to your microservice project. However, the shared library classes reside in package org.company.shared, while your main application resides in com.company.service. When the app boots, none of the utility beans are autowired. How do you resolve this?

View Solution

Since the libraries are outside the sub-package hierarchy of the main class, Spring's default scanning ignores them. Resolve this by modifying the @SpringBootApplication annotation (or declaring a separate @ComponentScan bean) to list both base packages: @SpringBootApplication(scanBasePackages = {"com.company.service", "org.company.shared"}).

Interview Questions

1. Conceptual: Why should you use @Repository instead of generic @Component for data access components?

Using @Repository enables Spring's **PersistenceExceptionTranslationPostProcessor**. This intercepts database-specific errors (like SQL exceptions, JPA persistence errors, or Hibernate-specific failures) and automatically translates them into Spring's standard, unified DataAccessException hierarchy, making error handling uniform and decoupled from database vendor details.

2. Technical: How does component scanning discover files without executing Java bytecode?

Spring uses an ASM-based metadata reader. Instead of loading every single class into the JVM's memory (classloader) which would be slow and might trigger static configuration code, Spring reads the compiled class files (bytecode) at the binary level, parsing the annotations in the class structure directly to decide if a bean definition should be generated.

Production Considerations

Keep your main class in the root package of your project (e.g. com.example.project) to make default scanning seamless. If you need to include utility beans or services from external packages, explicitly specify them in the scanBasePackages property of your main class definition. Avoid scan wildcard configurations that include test code or packages containing heavy non-bean classes.