Beans & Component Scanning
A bean is simply an object that the Spring container creates and manages. Spring decides when to create it, injects its dependencies, and (for most beans) keeps exactly one shared instance. The most common way to declare a bean is to put a stereotype annotation on a class and let component scanning find it.
Stereotype annotations
| Annotation | Use it for | Extra behaviour |
|---|---|---|
@Component |
any general-purpose bean | — |
@Service |
business logic | none (documents intent) |
@Repository |
data access classes | translates persistence exceptions into Spring's DataAccessException |
@Controller / @RestController |
web endpoints | registered as request handlers |
@Configuration |
classes that declare @Bean methods |
next lesson |
@Service, @Repository and @Controller are themselves annotated with @Component, so the scanner treats them all as components.
@Repository
class InMemoryTaskRepository implements TaskRepository { ... }
@Service
class TaskService {
private final TaskRepository repository;
TaskService(TaskRepository repository) { this.repository = repository; }
}
@RestController
class TaskController {
private final TaskService service;
TaskController(TaskService service) { this.service = service; }
}Bean names
Every bean has a name. For scanned classes, the default name is the simple class name with the first letter lower-cased: TaskService becomes taskService, InMemoryTaskRepository becomes inMemoryTaskRepository. You can choose one explicitly with @Service("tasks").
import java.beans.Introspector;
import java.util.List;
class Main {
// Spring's AnnotationBeanNameGenerator uses the same JDK rule
static String beanName(String simpleClassName) {
return Introspector.decapitalize(simpleClassName);
}
public static void main(String[] args) {
for (String cls : List.of("TaskService", "InMemoryTaskRepository", "URLShortener", "X")) {
System.out.printf("%-24s -> %s%n", cls, beanName(cls));
}
}
}TaskService -> taskService
InMemoryTaskRepository -> inMemoryTaskRepository
URLShortener -> URLShortener
X -> x
Note the special case: when the first two letters are upper case (URLShortener), the name is left unchanged.
How scanning works
At startup, Spring:
- reads every
.classfile under the base package (the package of your@SpringBootApplicationclass); - keeps the classes annotated with
@Componentor one of its specialisations; - registers a bean definition (class, name, scope, dependencies) for each;
- instantiates the singletons in dependency order.
Here is step 2 modelled with plain metadata records — each "class" carries its list of annotation names, and the scanner filters them:
import java.util.List;
import java.util.Set;
record ClassInfo(String name, List<String> annotations) {}
class Main {
static final Set<String> STEREOTYPES =
Set.of("Component", "Service", "Repository", "Controller", "RestController", "Configuration");
public static void main(String[] args) {
List<ClassInfo> classpath = List.of(
new ClassInfo("TaskController", List.of("RestController")),
new ClassInfo("TaskService", List.of("Service")),
new ClassInfo("Task", List.of()),
new ClassInfo("TaskRepository", List.of("Repository")),
new ClassInfo("TaskMapper", List.of("Component")),
new ClassInfo("StringUtils", List.of()));
int found = 0;
for (ClassInfo c : classpath) {
boolean bean = c.annotations().stream().anyMatch(STEREOTYPES::contains);
if (bean) found++;
System.out.printf("%-15s %s%n", c.name(), bean ? "-> bean" : "(plain class)");
}
System.out.println(found + " beans registered");
}
}TaskController -> bean
TaskService -> bean
Task (plain class)
TaskRepository -> bean
TaskMapper -> bean
StringUtils (plain class)
4 beans registered
Domain objects like Task and static helpers like StringUtils are not beans: you create them with new as usual. Only objects with dependencies or shared state need to be managed by Spring.
Seeing the beans in a running app
You can ask the context for its beans. A small CommandLineRunner (a bean whose run method executes once after startup) prints your own beans:
@Bean
CommandLineRunner listBeans(ApplicationContext ctx) {
return args -> Arrays.stream(ctx.getBeanDefinitionNames())
.filter(name -> ctx.getType(name).getPackageName().startsWith("com.example.tasks"))
.sorted()
.forEach(System.out::println);
}./mvnw -q spring-boot:runinMemoryTaskRepository
listBeans
taskController
taskService
tasksApplication
The main application class is a bean too — it is a @Configuration class underneath. A full application context of a web app typically contains a few hundred beans, most of them created by auto-configuration.
Customising the scan
You rarely need to, but scanning can be widened or filtered:
@SpringBootApplication(scanBasePackages = {"com.example.tasks", "com.example.shared"})
public class TasksApplication { ... }Tip: Prefer moving classes under the main package over adding
scanBasePackages. A predictable package structure is easier for everyone on the team.
Test yourself
What is the default bean name for a scanned class PriceCalculator?
PriceCalculatorpriceCalculatorprice-calculatorpriceCalculatorBean
Which stereotype adds translation of persistence exceptions?
@Service@Component@Repository@Controller
Should a JPA entity or a DTO record usually be a Spring bean?
- Yes, every class must be a bean
- No, they are plain data objects created with
newor by frameworks - Only if it has a constructor
- Only in tests