Sub topic 3
What a Spring bean is
This chapter assumes you know core Java (classes, interfaces, annotations) and have a Spring dependency on your classpath through Maven or Gradle. It does not cover how beans are discovered or wired. Later chapters do that.
A bean is an object the container manages
A Spring bean is an object whose creation, wiring and destruction are handled by the Spring container instead of your own code. The class itself is ordinary Java. It becomes a bean because Spring has a bean definition for it.
Compare the two approaches:
new PriceCache()gives you a plain object. Spring knows nothing about it.- A bean definition for
PriceCachetells Spring to create the object, supply its dependencies, and keep it for reuse.
This is inversion of control in practice. You describe what should exist, and the container decides when to build it.
What a bean definition holds
Spring stores a recipe for each bean before it creates anything. The recipe includes:
- The class to instantiate.
- A bean name, which is unique within the container.
- The scope, which controls how many instances exist. The default is singleton, one shared instance per container.
- The dependencies the bean needs.
- Optional initialization and destruction callbacks.
Because the recipe is data, Spring can validate it, reorder creation so dependencies come first, and report a missing dependency at startup instead of at the first call.
Seeing a bean in code
The example below registers one bean with a @Bean method, then asks the container for it in two ways. The @Configuration class is covered properly in a later chapter. Here it only supplies a definition.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class Main {
public interface MessageSender {
void send(String to, String body);
}
@Configuration
public static class AppConfig {
// The method name, emailSender, becomes the bean name.
@Bean
public MessageSender emailSender() {
return (to, body) -> System.out.println("email to " + to + ": " + body);
}
}
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
MessageSender byType = ctx.getBean(MessageSender.class);
MessageSender byName = ctx.getBean("emailSender", MessageSender.class);
System.out.println(byType == byName); // true
byType.send("ana", "Welcome!");
}
}
}Both lookups return the same object. That is the singleton scope at work: the container built the bean once and hands out that instance every time.
Beans are not every object
Most objects in an application should not be beans. Make something a bean when it is a shared collaborator, such as a service, repository, client or configuration holder. Keep data objects like an Order or a Customer as plain classes created with new. Those hold state that differs per use, and the container has no reason to manage them.
A singleton bean is shared across threads, so it should not hold mutable per-request state in its fields.
Common errors at this stage
| Error | Cause |
|---|---|
| `NoSuchBeanDefinitionException` | No bean of the requested type or name is registered. |
| `NoUniqueBeanDefinitionException` | More than one bean matches the requested type. |
| Dependency is `null` | You created the object with `new`, so the container never injected it. |
Exercise
In the example above, what would ctx.getBean("sender", MessageSender.class) do, and why?
Show answer
It would throw NoSuchBeanDefinitionException. The bean name comes from the @Bean method name, which is emailSender, so no bean named sender exists in the container.
Exercise
A class ReportRow holds data for one report line, and thousands of them are created per request. Should it be a bean?
Show answer
No. It is per-use data, not a shared collaborator. Create it with new, and leave the container to manage long-lived services.