Sub topic 6
Defining beans with @Component, @Service and component scanning
This chapter assumes you know core Java (classes, interfaces, constructors, annotations) and basic object-oriented design. It also assumes you have met the idea of a Spring bean and the ApplicationContext from earlier chapters. Here you will learn how to mark your own classes as beans and how Spring finds them.
The problem scanning solves
The container needs a list of bean definitions before it can create anything. You can write that list by hand with @Bean methods, which a later chapter covers. For classes you own, this gets tedious. Component scanning lets you annotate a class and have Spring discover it.
Scanning works in three steps:
- You mark a class with a stereotype annotation such as
@Component. - You tell Spring which packages to search.
- At startup, Spring reads the class files in those packages and registers a bean definition for each annotated class.
Spring reads class metadata and does not load the classes first. Registration happens before any bean is instantiated.
Stereotype annotations
A stereotype annotation marks a class as a bean and also says what role the class plays. @Component is the general one. The others are specializations that are themselves meta-annotated with @Component.
| Annotation | Intended layer | Extra behavior |
|---|---|---|
| `@Component` | Any class | None |
| `@Service` | Business logic | None, but documents intent |
| `@Repository` | Data access | Translates persistence exceptions to Spring's `DataAccessException` hierarchy |
| `@Controller` | Web layer (Spring MVC) | Detected as a request handler |
| `@RestController` | Web layer | `@Controller` plus `@ResponseBody` |
| `@Configuration` | Configuration class | Also a component, and processed for `@Bean` methods |
@Service adds no behavior of its own. Prefer it anyway, because it tells readers which layer the class belongs to. Tools and aspects can also target it, for example with a pointcut on all @Service classes.
public interface MessageSender {
void send(String to, String body);
}
@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!");
}
}NotificationService never creates a MessageSender. It declares the need in its constructor, and Spring supplies a matching bean.
Turning scanning on
Scanning is not automatic in plain Spring. Something must request it. There are two common ways.
With @ComponentScan
Place @ComponentScan on a configuration class and name the packages to search.
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example.shop")
public class AppConfig {
}If you omit basePackages, Spring scans the package of the annotated class and all its sub-packages. You can also use basePackageClasses, which takes marker classes. This is refactoring-safe because renaming a package updates the reference.
With Spring Boot
@SpringBootApplication combines three annotations: @Configuration, @EnableAutoConfiguration and @ComponentScan. The scan starts at the package of the class that carries it.
package com.example.shop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}Beans in com.example.shop.orders are found. Beans in com.example.other are not.
How scanning looks from the outside
The separation between registering definitions and creating instances matters. Spring can check the whole set of definitions, order creation by dependency, and detect problems such as a missing bean before your code runs.
Bean names
Each bean gets a name. For scanned classes, the default is the simple class name with the first letter lowercased. NotificationService becomes notificationService.
You can set a name explicitly through the annotation value:
@Service("welcomeNotifier")
public class NotificationService {
// ...
}Names matter in two places. @Qualifier can select a bean by name, and two beans with the same name in one context conflict. In recent Spring versions, a duplicate name from a scanned class raises ConflictingBeanDefinitionException. This can happen with two classes called Config in different packages. Give one an explicit name.
Running it
The following example builds a context from a scanning configuration and uses a scanned bean. It assumes the classes above live in the package that AppConfig scans, and that some bean implements MessageSender. The ConsoleSender below provides one.
package com.example.shop;
import org.springframework.stereotype.Component;
@Component
public class ConsoleSender implements MessageSender {
@Override
public void send(String to, String body) {
System.out.println("to " + to + ": " + body);
}
}import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
NotificationService service = ctx.getBean(NotificationService.class);
service.welcome("ana");
}
}
}Running this prints to ana: Welcome!. Neither class was registered by hand. If AppConfig is in com.example.shop, @ComponentScan with no arguments finds both.
Filters: narrowing and widening a scan
@ComponentScan accepts filters. Use them when a package contains classes you want to leave out, or classes without annotations that you want to include.
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.FilterType;
@Configuration
@ComponentScan(
basePackages = "com.example.shop",
excludeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Legacy.*")
)
public class FilteredConfig {
}Available filter types include ANNOTATION, ASSIGNABLE_TYPE, ASPECTJ, REGEX and CUSTOM. Exclusion is the more common use. Inclusion filters are rare, because adding an annotation to the class is usually clearer.
Edge cases and gotchas
- Abstract classes and interfaces are skipped. Scanning registers only concrete classes. Annotating an interface with
@Componentdoes nothing for the interface itself. - No-argument constructor is not required. Spring uses the single constructor or the one marked
@Autowired. If a class has several constructors and none is marked, Spring needs a no-argument one. Without it, startup fails. - Stereotypes on inner classes. A static nested class is scanned. A non-static inner class needs an instance of its outer class, so it is generally not usable as a bean.
- Meta-annotations compose. You can create your own stereotype by annotating an annotation with
@Component. Spring then treats classes with your annotation as components. - Overlapping scans. If two
@ComponentScandeclarations cover the same package, Spring registers each class once. It does not create duplicates, but the overlap makes the configuration harder to read. - Scanned configuration classes. A
@Configurationclass inside a scanned package is picked up too. This is convenient, and it can surprise you when a test configuration is loaded in production. Profiles, covered in a later chapter, are the usual remedy. - Third-party classes. You cannot add
@Componentto a library class. Use an@Beanmethod for those.
A custom stereotype looks like this:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface Handler {
}Any class annotated with @Handler is now registered by scanning.
Choosing between scanning and @Bean
| Situation | Better choice |
|---|---|
| Your own class with a simple constructor | Stereotype and scanning |
| Library class you cannot edit | `@Bean` method |
| Construction needs logic or several steps | `@Bean` method |
| Several differently configured instances of one type | `@Bean` methods |
| You want the layer visible in the class itself | Stereotype annotation |
The two approaches mix freely in one application. Many projects scan for application classes and use @Bean methods for infrastructure.
Exercise
A Spring application has its main class in com.example.app and a class PriceService, annotated with @Service, in com.example.pricing. Injecting PriceService fails with NoSuchBeanDefinitionException. What is the likely cause, and what are two ways to fix it?
Show answer
The scan starts at com.example.app, so com.example.pricing is outside the scanned tree and PriceService is never registered. Fix it by moving the main class to the common root package com.example, or by naming the extra package explicitly, for example @SpringBootApplication(scanBasePackages = {"com.example.app", "com.example.pricing"}) or with @ComponentScan.
Exercise
What bean name does Spring give to a scanned class OrderRepository annotated with @Repository, and how would you override it?
Show answer
The default name is orderRepository. Override it with the annotation value, for example @Repository("orders").