Sub topic 1
The container and what it manages
Prerequisites
This chapter assumes you already know:
- Core Java, including interfaces, annotations, and how a
mainmethod starts a program. - Basic Spring dependency injection:
@Component,@Autowired,@Configuration, and@Bean. - How to build and run a Spring or Spring Boot application.
You do not need to know anything about lifecycle callbacks or scopes yet. Later chapters cover them. This chapter sets up the vocabulary they rely on.
What the container is
In a plain Java program, your code creates objects with new and passes them to each other. In Spring, you describe the objects you need and the container creates and connects them. This pattern is called inversion of control (IoC): control over object creation moves from your code to the framework.
The container is a runtime object that does four jobs:
- It reads descriptions of your objects.
- It creates the objects.
- It supplies each object with the other objects it depends on.
- It manages each object's life, from creation to shutdown.
An object that the container creates and manages is called a bean. An ordinary object made with new inside your own code is not a bean, even if its class is annotated with @Component. The container knows nothing about it, so it never injects dependencies into it or calls any callbacks on it.
BeanFactory and ApplicationContext
Spring has two container interfaces.
BeanFactoryis the basic one. It can create beans, inject dependencies, and look beans up by name or type.ApplicationContextextendsBeanFactoryand adds features that real applications need: event publishing, message resolution for internationalization, resource loading, environment and property access, and automatic registration of infrastructure beans such asBeanPostProcessors.
In practice you almost always work with an ApplicationContext. Spring Boot creates one for you when you call SpringApplication.run. The BeanFactory still exists inside it, and the context delegates bean creation to it.
| Interface | Creates and injects beans | Detects `BeanPostProcessor` beans automatically | Publishes events | Typical use |
|---|---|---|---|---|
| `BeanFactory` | Yes | No, you register them by hand | No | Very small or embedded setups |
| `ApplicationContext` | Yes | Yes | Yes | Almost every application |
A few concrete ApplicationContext classes appear often:
AnnotationConfigApplicationContextbuilds a context from@Configurationclasses. It is the one to use in plain Java programs and tests.AnnotationConfigServletWebServerApplicationContextis what Spring Boot creates for a servlet web application.GenericApplicationContextis a flexible base class that lets you register bean definitions in code.
What the container manages
The container manages three things for every bean.
Creation. It chooses a constructor or factory method, resolves the arguments, and calls it.
Wiring. It injects dependencies through the constructor, setter methods, or fields.
Lifetime. It decides when the bean is created, how many instances exist, and when the bean is shut down. The number of instances and their lifespan are set by the bean's scope. The default scope is singleton, which means one shared instance per container.
Lifetime is the subject of most of this tutorial. Two topics fill most of it. The lifecycle is the sequence of steps a bean goes through. The scope is the rule that governs how many instances exist and for how long.
Bean definitions
The container does not work from your Java classes directly. It works from bean definitions. A bean definition is a recipe that holds the information the container needs to build one bean. It includes:
- The class to instantiate, or the factory method to call.
- The bean's name and any aliases.
- The scope, such as singleton or prototype.
- Constructor arguments and property values.
- Whether the bean is lazy, which controls when it is created.
- Names of initialization and destruction methods.
- Dependencies on other beans.
Several mechanisms produce bean definitions:
| Source | How the definition is created |
|---|---|
| `@Component` and its variants (`@Service`, `@Repository`, `@Controller`) | Component scanning finds annotated classes on the classpath |
| `@Bean` methods in a `@Configuration` class | Each method becomes a factory method for one definition |
| `@Import` and `@ImportSelector` | Other configuration classes or computed class names are added |
| Spring Boot auto-configuration | Conditional configuration classes add definitions when conditions hold |
| Programmatic registration | Your code calls `registerBean` or `registerBeanDefinition` |
The key point is that a definition is only a description. Reading the definitions and creating the beans are separate steps, and Spring runs them in that order. Because the definitions exist before any bean is built, Spring can inspect and change them. A component called a BeanFactoryPostProcessor does exactly that. It runs after all definitions are loaded and before any ordinary bean is created. Later chapters contrast it with the BeanPostProcessor, which acts on bean instances instead of definitions.
From definition to instance
The following diagram shows the overall flow at startup and shutdown.
Here is what each step means.
- Load bean definitions. The container scans packages, reads
@Configurationclasses, and registers a definition for each bean. - Post-process definitions.
BeanFactoryPostProcessors may edit definitions. Property placeholders such as${server.port}are resolved at this point. - Create singleton beans. The container instantiates every non-lazy singleton, injects its dependencies, and runs its initialization steps. The next chapters break this step into smaller phases.
- Application runs. Code asks the context for beans, or receives them by injection. Beans in other scopes, such as prototype and request, are created on demand during this phase.
- Close context. Closing the context destroys singleton beans and calls their destruction callbacks.
Step 3 has a consequence worth remembering: by default, singleton beans are created at startup, not when first used. A broken singleton fails the whole application at launch. That is usually what you want, because configuration mistakes show up immediately.
Seeing the container at work
The program below creates a context from a configuration class, asks it for a bean, and closes it. It uses only the pieces described above.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class ContainerDemo {
static class Greeter {
Greeter() {
System.out.println("Greeter created");
}
String greet() {
return "hello";
}
}
@Configuration
static class AppConfig {
@Bean
Greeter greeter() {
return new Greeter();
}
}
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class)) {
System.out.println("context started");
Greeter first = ctx.getBean(Greeter.class);
Greeter second = ctx.getBean("greeter", Greeter.class);
System.out.println(first.greet());
System.out.println("same instance: " + (first == second));
}
}
}The output is:
Greeter created
context started
hello
same instance: trueTwo details matter here.
Greeter createdprints beforecontext started. The singleton was built while the context was being constructed, not whengetBeanwas called.- Both lookups return the same object. Singleton scope means one instance per container, no matter how many times you ask for it.
The try block closes the context when it ends. Closing is what triggers destruction callbacks on singletons. Without it, a plain Java program would exit without telling the beans to shut down. Spring Boot registers a JVM shutdown hook for you, so you rarely think about this in a Boot application.
Common mistakes
- Creating a managed class with
new.new Greeter()in your own code gives an object with no injected fields and no callbacks. Ask the container for it, or inject it. - Expecting a definition to be an instance. Annotating a class registers a recipe. The instance exists only after the container builds it.
- Using one context per request or per test method by accident. Each
ApplicationContextholds its own singletons. Two contexts mean two "singletons" of the same class. - Forgetting to close a context in a plain Java program. Singleton destruction callbacks never run, so resources such as connection pools may not be released cleanly.
What comes next
The next chapters follow one bean through its life. You will see how the container builds the instance and wires it, what callbacks run and in what order, and how scope changes the picture. The terms defined here recur throughout: container, bean, bean definition, and scope.
Exercise
A class is annotated with @Component, and your own method calls new on it and uses the result. Is that object a Spring bean, and will Spring inject its @Autowired fields?
Show answer
No. A bean is an object that the container creates and manages. An object made with new in your own code is unknown to the container, so Spring does not inject its fields or call its lifecycle callbacks. The @Component annotation only registers a bean definition. The container-built instance is the bean, and you get it by injection or by getBean.
Exercise
In the ContainerDemo program, what changes in the output if the @Bean method is replaced so that the Greeter is created lazily (only on first request), and why does "same instance" still print true?
Show answer
"Greeter created" would print after "context started", at the first getBean call, because a lazy singleton is built on first use instead of at startup. "same instance" still prints true because laziness changes only when the singleton is created. It remains a singleton, so both lookups return the same object.
Exercise
What is the difference between a bean definition and a bean instance, and why does the container separate loading definitions from creating beans?
Show answer
A bean definition is a recipe: class or factory method, scope, constructor arguments, lazy flag, and callback names. A bean instance is the object built from that recipe. The container loads all definitions first so that BeanFactoryPostProcessors can inspect and change them, for example by resolving property placeholders, before any ordinary bean is created.