Sub topic 2
From bean definition to bean instance
This chapter assumes you know core Java, the basic Spring annotations (@Component, @Autowired, @Configuration, @Bean), and how to run a Spring or Spring Boot application. It covers how the container turns a recipe for a bean into a working object. Later chapters cover the callbacks and scopes in detail.
A definition is a recipe, not an object
Spring does not start by creating objects. It starts by building a catalog of bean definitions. A BeanDefinition is a metadata object that describes how to build one bean. It records:
- The class name, or the factory method that produces the instance.
- The scope, such as singleton or prototype.
- Whether the bean is lazy.
- Constructor arguments and property values.
- Names of beans it depends on (
dependsOn). - Names of the init and destroy methods.
- Flags such as
primaryandautowireCandidate.
The container stores these definitions in a registry, which is a map from bean name to definition. In an ApplicationContext, the registry is a DefaultListableBeanFactory. Creating the actual object happens later, and for most beans it happens only once.
Where definitions come from
Definitions are registered by several mechanisms, and all of them end up in the same registry.
| Source | How the definition is created |
|---|---|
| `@Component` and stereotypes | Classpath scanning (`@ComponentScan`) finds annotated classes and registers one definition per class. |
| `@Bean` methods | Each method in a `@Configuration` class becomes a definition whose instance comes from calling the method. |
| `@Import` | Pulls in other configuration classes, or an `ImportSelector` or `ImportBeanDefinitionRegistrar` that registers definitions programmatically. |
| XML | `<bean>` elements are parsed into definitions. |
| Programmatic | You call `registerBeanDefinition` or `registerBean` on the context. |
The default bean name for a scanned class is the uncapitalized simple class name, so OrderService becomes orderService. For a @Bean method it is the method name. Two definitions with the same name are a conflict. Spring Boot disables overriding by default and fails at startup. Plain Spring allows overriding, so the later definition silently wins.
The refresh sequence
When you create an AnnotationConfigApplicationContext or start Spring Boot, the context runs refresh(). The steps that matter for this chapter are:
- Load all bean definitions. Scanning and configuration parsing happen here.
- Run
BeanFactoryPostProcessors. These can read and change definitions before any normal bean exists. - Register
BeanPostProcessors, so they are ready to wrap beans created afterwards. - Instantiate all non-lazy singletons.
- Publish the context-refreshed event.
The important point is the gap between steps 1 and 4. Between registration and instantiation, definitions are still data, and BeanFactoryPostProcessors can edit them. For example, PropertySourcesPlaceholderConfigurer resolves ${...} placeholders in definitions at this stage. ConfigurationClassPostProcessor, which Spring registers itself, is what actually parses @Configuration, @ComponentScan and @Bean.
Seeing a definition
You can inspect a definition yourself. This program registers a component by scanning and prints what the registry knows about it before any instance is requested.
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
public class DefinitionDemo {
static class Greeter {
Greeter() {
System.out.println("Greeter constructed");
}
}
@Configuration
static class Config {
@Bean
@Lazy
@Scope("singleton")
Greeter greeter() {
return new Greeter();
}
}
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(Config.class)) {
BeanDefinition bd = ctx.getBeanFactory().getBeanDefinition("greeter");
System.out.println("scope = " + bd.getScope());
System.out.println("lazy = " + bd.isLazyInit());
System.out.println("factory method = " + bd.getFactoryMethodName());
System.out.println("before getBean");
ctx.getBean(Greeter.class);
System.out.println("after getBean");
}
}
}The output is:
scope = singleton
lazy = true
factory method = greeter
before getBean
Greeter constructed
after getBeanThe definition exists and is fully described before the constructor runs. Because the bean is @Lazy, the instance appears only at the first getBean. Without @Lazy, "Greeter constructed" would print before the first line.
From definition to instance
When the container needs a bean, getBean(name) goes through a fixed path in AbstractBeanFactory and AbstractAutowireCapableBeanFactory:
- Resolve the name. Aliases are mapped to the canonical name.
- Check the cache. For a singleton, the container looks in its singleton registry. If an instance is already there, it returns it and stops.
- Merge definitions. If the definition has a parent definition, the container combines them into a single merged definition.
- Create dependencies named in
dependsOn. These beans are created first, and the order matters for beans that depend on each other only through side effects. - Instantiate. The container picks a constructor or calls the factory method.
- Populate properties. It injects
@Autowiredfields and setters. - Initialize. It runs the Aware callbacks, post-processors and init methods.
- Register for destruction if the bean has destroy callbacks and its scope is managed by the container.
- Cache the instance when the scope is singleton.
Steps 5 and 6 are the subject of the next chapter, and step 7 is the subject of the chapters after it. What matters here is that the definition drives every step.
Constructors and factory methods
How the container instantiates a bean depends on the definition.
- Class with one constructor. Spring uses it. Since Spring 4.3 you do not need
@Autowiredon a single constructor. - Class with several constructors. Spring needs a hint. Mark one with
@Autowired, or provide a no-argument constructor as the fallback. @Beanmethod. The container calls the method as a factory. Its parameters are resolved as dependencies, exactly like constructor parameters.FactoryBean. The container instantiates the factory bean, then asks it for the real object.getBean("name")returns the product, andgetBean("&name")returns the factory.
The @Bean case has a trap. In a @Configuration class, Spring wraps the class in a CGLIB subclass, so a call from one @Bean method to another returns the cached bean instead of creating a second one. In a class marked @Configuration(proxyBeanMethods = false), or in a plain @Component, there is no such interception, and the second call builds a new object.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class ShopConfig {
static class Clock {
}
static class Cart {
final Clock clock;
Cart(Clock clock) {
this.clock = clock;
}
}
@Bean
Clock clock() {
return new Clock();
}
@Bean
Cart cart() {
// With proxyBeanMethods = true (the default), this is the singleton Clock bean.
return new Cart(clock());
}
}The safer form takes Clock as a parameter of cart(Clock clock). It works under every configuration mode.
Bean names, types and ambiguity
The registry is keyed by name, but you usually ask by type. When several definitions match a type, the container applies its selection rules in order:
- A definition marked
@Primary. - A match between the injection point's parameter or field name and a bean name.
- A
@Qualifieron the injection point, which in practice is checked before the name fallback. A qualifier narrows candidates first.
If more than one candidate remains, the container throws NoUniqueBeanDefinitionException. If none remain, it throws NoSuchBeanDefinitionException. Both errors are raised at startup for singletons, which is one reason to prefer eager singletons: wiring mistakes surface when the application starts and not on the first request.
Common errors at this stage
BeanDefinitionOverrideException. Two definitions share a name. Rename one, or setspring.main.allow-bean-definition-overriding=trueonly if the override is intended.NoSuchBeanDefinitionException. No definition matches. The class is usually outside the scanned packages, or a conditional such as@ConditionalOnPropertyexcluded it.UnsatisfiedDependencyException. A definition was found, but one of its dependencies could not be built. The root cause is at the bottom of the exception chain.BeanCurrentlyInCreationException. Two beans depend on each other through constructors, so neither can be built first. Spring Boot forbids circular references by default. Break the cycle by redesigning, not by enabling them.- A
BeanFactoryPostProcessorthat triggers early creation. Declaring one as a non-static@Beanmethod forces its configuration class to be created too early, and other beans in that class miss post-processing. Declare such methodsstatic.
Exercise
A @Component class has @Lazy on it and a constructor that prints a line. The application starts, and no request ever uses the bean. Is the line printed, and does the container still hold a definition for the bean?
Show answer
The line is not printed, because a lazy singleton is only instantiated at its first getBean or injection. The container still holds the definition from the start, since definitions are registered during refresh whether or not the bean is lazy. You can confirm it with getBeanDefinition("name"), which succeeds before the bean is ever created.
Exercise
Why can a BeanFactoryPostProcessor change a bean's scope or constructor arguments, but a BeanPostProcessor cannot?
Show answer
A BeanFactoryPostProcessor runs after definitions are loaded and before any regular bean is instantiated, so it can edit the recipe. A BeanPostProcessor runs per bean instance, after the container has already chosen the constructor and built the object. At that point it can only inspect or replace the finished instance.