Sub topic 3
What a Spring Bean Is
This chapter assumes you know core Java (classes, interfaces, constructors, annotations), basic object-oriented design, and how to add a dependency in Maven or Gradle. It defines the term "bean", shows what separates a bean from an ordinary object, and covers the metadata Spring keeps about each bean. It does not cover scanning, scopes or lifecycle in detail. Later chapters do.
The definition
A Spring bean is an object whose creation, wiring and destruction are managed by the Spring container. The container is an ApplicationContext, which a later chapter covers. The class of a bean is plain Java. Nothing in the language marks it as special. What makes it a bean is that the container instantiates it, or at least registers it, and keeps a record of it.
Consider two ways to get a NotificationService:
// Not a bean: you create it and you hold the only reference.
NotificationService manual = new NotificationService(sender);
// A bean: the container creates it and hands it out on request.
NotificationService managed = ctx.getBean(NotificationService.class);Both objects have the same class. Only the second is a bean. The first is invisible to Spring, so it gets no injection, no lifecycle callbacks and no proxies.
This difference has a practical consequence. Annotations such as @Autowired or @Value only work on beans. If you write new NotificationService(...) inside another bean's method, any annotated fields on the new object stay empty.
What the container records about a bean
For each bean the container keeps a bean definition. A bean definition is a recipe that describes how to produce the bean. It holds:
- The class to instantiate, or the factory method that produces the object.
- The scope, such as singleton or prototype.
- The constructor arguments and property values, or the dependencies to resolve.
- Initialization and destruction callbacks.
- Whether the bean is lazy, and whether it is the primary candidate for its type.
The container builds the definitions first. It creates instances afterward, using the definitions as input. This two-phase model explains several behaviors you will meet later. For example, the container can detect a missing dependency or a duplicate bean before it creates any object.
The diagram below shows the sequence.
Bean names and types
Every bean has at least one name, called its bean id, and a type. Spring uses both to find beans.
- With
@Componentand related annotations, the default name is the simple class name with a lowercase first letter.NotificationServicebecomesnotificationService. - With
@Bean, the default name is the method name. A method calledemailSenderproduces a bean namedemailSender. - You can override either default, for example
@Bean("mailer")or@Service("notifier").
Lookup by type is the normal path. Lookup by name is mostly used to disambiguate, which a later chapter on @Primary and @Qualifier covers.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class LookupDemo {
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);
}
}
}This prints true when AppConfig from the earlier example defines one MessageSender, because both calls return the same singleton instance.
Calling getBean directly is fine in a main method or a test. Inside application classes, prefer declaring the dependency as a constructor parameter. Calling getBean from business code hides dependencies and brings back the coupling that injection is meant to remove.
The three ways a bean comes into existence
A class becomes a bean in one of three ways. Each is covered in its own chapter, so this section only names them.
| Mechanism | Where you write it | Typical use |
|---|---|---|
| Stereotype annotation plus component scanning | On the class: `@Component`, `@Service`, `@Repository`, `@Controller` | Classes you own |
| `@Bean` method in a `@Configuration` class | In a configuration class | Third-party classes, or beans needing construction logic |
| Programmatic registration | Through the container's API | Frameworks and unusual cases |
The first two cover almost all application code. Programmatic registration exists, but you rarely need it.
Beans are singletons by default
If you do not say otherwise, the container creates one instance of each bean and shares it. This is the singleton scope. Every class that depends on MessageSender receives the same object.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SingletonDemo {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
NotificationService first = ctx.getBean(NotificationService.class);
NotificationService second = ctx.getBean(NotificationService.class);
System.out.println(first == second);
}
}
}The output is true.
A Spring singleton differs from the singleton design pattern. The pattern guarantees one instance per class loader, usually through a static field. A Spring singleton means one instance per container, per bean definition. If you define two beans of the same class under different names, you get two instances. If you create two containers, each has its own copy.
The default has a design consequence. A singleton bean is shared across threads, so it should not hold mutable per-request state in its fields. Keep beans stateless, or make any state thread-safe. A bean that stores the current user in a field works in a single-threaded test and fails under concurrent load.
@Service
public class ReportService {
// Unsafe: shared by every thread that uses this bean.
private String currentUser;
public String build(String user) {
this.currentUser = user;
return "Report for " + currentUser;
}
}Two concurrent calls can overwrite currentUser before the string is built. Use a local variable instead:
@Service
public class ReportService {
public String build(String user) {
return "Report for " + user;
}
}Beans do not have to be created by you
A common misreading is that the container always calls your constructor. It usually does, but the bean can come from other sources:
- A constructor, for classes found by scanning.
- A factory method, for
@Beanmethods. The method body decides how the object is built, including callingnewon a class you do not control. - A
FactoryBean, a special bean type whose job is to produce another object. Spring itself uses this for some infrastructure.
From the point of view of code that receives the injected object, the source does not matter. It sees a MessageSender either way.
Proxies: the bean you get may not be the object you wrote
The container can wrap a bean in a proxy before handing it out. A proxy is a generated object that stands in for the real one and adds behavior around method calls. Features such as @Transactional, @Async and @Cacheable work this way.
This affects what you see at runtime:
ctx.getBean(Foo.class).getClass()may return a generated subclass, notFoo.- Calling a method on
thisinside the bean bypasses the proxy, so the added behavior does not run for that call. - Declaring a bean's methods or class
finalcan stop class-based proxying.
For now, remember one point. The reference you inject is the container's version of the bean, and it may be a wrapper. Later chapters return to this when they cover lifecycle and scopes.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Creating a bean-class instance with `new` and expecting injection | `NullPointerException` on an annotated field | Receive the object through the container instead |
| Forgetting to register the class | `NoSuchBeanDefinitionException` at startup | Add a stereotype annotation within a scanned package, or add a `@Bean` method |
| Two beans of the same type and no selection rule | `NoUniqueBeanDefinitionException` | Use `@Primary` or `@Qualifier` |
| Storing request state in a singleton field | Wrong data under concurrency | Keep the bean stateless, or choose a narrower scope |
| Calling `getBean` in business code | Hidden dependencies, hard tests | Use constructor injection |
Summary of the model
- Configuration sources describe beans as bean definitions.
- The container reads the definitions, then creates and wires the instances.
- Each bean has a name and a type, and by default exactly one shared instance.
- What you receive may be a proxy around your class.
- Only objects the container manages receive container features.
Exercise
A class PriceService is annotated with @Service and has a field @Autowired private PriceRepository repo;. A developer writes PriceService s = new PriceService(); in a utility method and calls s.lookup("A1"), which uses repo. What happens, and why?
Show answer
The call throws a NullPointerException because repo is null. The new operator creates an ordinary object that the container does not know about, so no injection happens, even though the class has @Service. The fix is to obtain the instance from the container, usually by declaring PriceService as a constructor parameter of the class that needs it.
Exercise
Your application defines two @Bean methods, emailSender and smsSender, both returning MessageSender. Without any extra annotations, what are the bean names and what error occurs when a class requests a single MessageSender?
Show answer
The bean names are emailSender and smsSender, taken from the method names. Requesting one MessageSender by type finds two candidates, so the container throws NoUniqueBeanDefinitionException. Marking one bean @Primary or using @Qualifier at the injection point resolves it.
Exercise
A singleton @Service keeps the current customer id in a private field that each method call sets. Why is this a bug, and what are two ways to fix it?
Show answer
One instance is shared by all threads, so concurrent calls overwrite each other's value. Fix it by passing the customer id as a method parameter or local variable so the bean stays stateless, or by giving the bean a narrower scope such as prototype or request, so each use gets its own instance.