Sub topic 6
Defining beans with @Component, @Service and component scanning
This chapter assumes you know Java annotations and constructors, and that you have seen what a bean is and what the ApplicationContext does. Here you will learn how Spring finds classes and registers them as beans without a line of manual wiring.
Stereotype annotations
A stereotype annotation marks a class as a bean candidate. @Component is the general one. The others are specializations of it:
| Annotation | Intended layer | Extra behavior |
|---|---|---|
| `@Component` | Any class | None |
| `@Service` | Business logic | None, but documents intent |
| `@Repository` | Data access | Translates persistence exceptions |
| `@Controller` | Web layer | Handles web requests |
@Service behaves like @Component today. Choose the most specific annotation anyway, because tools and readers use it to understand your design.
Component scanning
Annotating a class does nothing by itself. Spring registers it only when component scanning looks in its package. Scanning walks the classpath under a base package and registers every class that carries a stereotype annotation.
A working example
Assume this layout:
com.example.notify
├── AppConfig.java
├── EmailSender.java
├── MessageSender.java
├── Main.java
└── NotificationService.java// MessageSender.java
package com.example.notify;
public interface MessageSender {
void send(String to, String body);
}// EmailSender.java
package com.example.notify;
import org.springframework.stereotype.Component;
@Component
public class EmailSender implements MessageSender {
@Override
public void send(String to, String body) {
System.out.println("email to " + to + ": " + body);
}
}// NotificationService.java
package com.example.notify;
import org.springframework.stereotype.Service;
@Service
public class NotificationService {
private final MessageSender sender;
// With a single constructor, @Autowired is optional.
public NotificationService(MessageSender sender) {
this.sender = sender;
}
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}// AppConfig.java
package com.example.notify;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.example.notify")
public class AppConfig {
}// Main.java
package com.example.notify;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
ctx.getBean(NotificationService.class).welcome("ana");
}
}
}Running Main prints email to ana: Welcome!. Scanning finds EmailSender and NotificationService. Spring then injects the EmailSender into the service because it is the only bean of type MessageSender.
Bean names
Each scanned bean gets a default name: the simple class name with a lowercase first letter. EmailSender becomes emailSender. Override it with @Service("notifier"). Names matter when you use @Qualifier, which a later chapter covers.
Scanning in Spring Boot
@SpringBootApplication includes @ComponentScan. It scans the package of the annotated class and all its subpackages. Put your main class in a root package such as com.example.notify, and keep other classes below it.
Common errors
- Class outside the scanned package. The class is never registered. You then see
NoSuchBeanDefinitionExceptionorNoSuchBeanDefinitionException: No qualifying bean of type ...at the injection point. Fix it by moving the class or widening the scan with@ComponentScan(basePackages = {...}). - Missing annotation. A class with no stereotype is invisible to scanning, even in the right package.
- Two implementations of one interface. Injection by type becomes ambiguous. Resolve it with
@Primaryor@Qualifier. - Scanning too broadly. Pointing at a very high package, such as
com, slows startup and can register unrelated beans.
Exercise
You add @Service to ReportService in package com.example.reports. Your @SpringBootApplication class is in com.example.app. Injecting ReportService fails with "No qualifying bean". Why, and how do you fix it?
Show answer
The default scan covers only com.example.app and its subpackages, so com.example.reports is never scanned. Move ReportService under com.example.app, or move the main class to the common parent com.example. Alternatively, add @ComponentScan or scanBasePackages = {"com.example.app", "com.example.reports"} to cover both packages.