Sub topic 2
From bean definition to bean instance
This chapter assumes you know @Component, @Configuration and @Bean, and can run a Spring application. It shows what the container stores before it creates any object. Many startup errors and surprises come from this stage.
A definition is not an instance
Spring does not start by creating objects. It first reads your configuration and builds a bean definition for each bean. A bean definition is a metadata object (BeanDefinition) that describes how to create a bean. It records:
- the class, or the factory method for
@Bean - the scope
- whether it is lazy
- constructor arguments and property values
initMethodanddestroyMethodnames@DependsOnand@Primarysettings
The container keeps these definitions in a registry that maps bean names to definitions. Definitions can come from component scanning, @Bean methods, @Import, XML, or code such as registerBean. Whatever the source, they all end up in the same registry.
The path to an instance
All of this happens inside refresh(). Three points matter:
- Definitions are complete before any application bean is created. A
BeanFactoryPostProcessorcan change them. For example,PropertySourcesPlaceholderConfigurerresolves${...}placeholders in them. - Singletons that are not lazy are created at the end of
refresh(). A broken wiring therefore fails at startup, not on first use. - Prototype and lazy beans stay as definitions until something asks for them.
Inspecting definitions
This program prints what the registry knows, without creating the prototype bean.
import java.util.List;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
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;
@Configuration
class AppConfig {
@Bean
Greeter greeter() {
return new Greeter();
}
@Bean
@Lazy
@Scope("prototype")
Ticket ticket() {
return new Ticket();
}
}
class Greeter {
}
class Ticket {
}
public class DefinitionDemo {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.register(AppConfig.class);
ctx.refresh();
ConfigurableListableBeanFactory factory = ctx.getBeanFactory();
for (String name : List.of("greeter", "ticket")) {
BeanDefinition bd = factory.getBeanDefinition(name);
System.out.println(name
+ " singleton=" + bd.isSingleton()
+ " prototype=" + bd.isPrototype()
+ " lazy=" + bd.isLazyInit());
}
}
}
}Expected output:
greeter singleton=true prototype=false lazy=false
ticket singleton=false prototype=true lazy=trueUse isSingleton() and isPrototype() instead of getScope(). For a @Bean method with no @Scope, getScope() returns an empty string.
Common errors at this stage
| Error | Cause |
|---|---|
| `NoSuchBeanDefinitionException` | No definition matches the requested name or type. Check component scan packages and conditions. |
| `NoUniqueBeanDefinitionException` | Several definitions match a type. Use `@Primary` or `@Qualifier`. |
| `BeanDefinitionOverrideException` | Two definitions use the same name. Spring Boot forbids overriding by default. |
Exercise
A bean marked @Lazy has a constructor that throws an exception. When does the failure appear, and why?
Show answer
It appears on first use, for example the first getBean call or the first injection point that resolves it. The lazy bean exists only as a bean definition until then, because the container instantiates only non-lazy singletons at the end of refresh().