Inversion of control and the Spring IoC container
Inversion of control means your classes stop creating and calling the objects they depend on; something outside them does it. This page shows the idea in plain Java first, builds a 40-line container to show what one does underneath, then looks at how Spring's BeanFactory and ApplicationContext read definitions, create beans and call your code back.
Contents
What inversion of control means Inverting control by hand What a container does underneath The Spring container: definitions first, then beans BeanFactory and ApplicationContext Registering beans with code Inversion of control beyond injection Common misunderstandings Choosing how to set up the container
What inversion of control means
In an ordinary program, each class is in charge of its own collaborators. A notepad that needs a spell checker writes new EnglishSpellChecker()
With inversion of control (IoC), the class gives that control away. It declares that it needs a SpellChecker
IoC is the principle; there are several ways to apply it:
| Form | What is inverted | Spring example |
|---|---|---|
| Dependency injection | Creating and choosing collaborators | Constructor parameters filled by the container |
| Callbacks (template method) | The control flow around your code | JdbcTemplateRowMapper |
| Events | Who calls whom | @EventListener |
| Lifecycle callbacks | When setup and cleanup run | @PostConstruct@PreDestroy |
| Service locator (the opposite of injection) | Only creation; the class still asks for its collaborators | context.getBean(...) |
An IoC container is the piece of software that does the creating and wiring for a whole application. It reads a description of the objects (in Spring, bean definitions), works out the dependencies between them, creates them in the right order, and keeps the ones that should be shared. Spring's container is the core of the framework: transactions, web controllers, security and Spring Boot's auto-configuration are all beans that it creates and wires.
The first two examples use only the JDK, to show the idea and a container's mechanics without Spring. The others use Spring Framework 7.0 without Spring Boot.
Inverting control by hand
A tightly coupled notepad and an inverted one, given the same sentence with one misspelled word, teh
import java.util.List;
import java.util.Set;
public class ManualWiring {
interface SpellChecker {
List<String> misspelled(String text);
}
static class EnglishSpellChecker implements SpellChecker {
private final Set<String> dictionary = Set.of("the", "cat", "sat", "on", "mat");
@Override
public List<String> misspelled(String text) {
return List.of(text.split(" ")).stream()
.filter(word -> !dictionary.contains(word)).toList();
}
}
static class NoOpSpellChecker implements SpellChecker {
@Override
public List<String> misspelled(String text) {
return List.of();
}
}
// Control in the class: it decides which spell checker exists.
static class TightNotepad {
private final SpellChecker checker = new EnglishSpellChecker();
String check(String text) {
return "misspelled " + checker.misspelled(text);
}
}
// Control inverted: whoever creates the notepad decides.
static class Notepad {
private final SpellChecker checker;
Notepad(SpellChecker checker) {
this.checker = checker;
}
String check(String text) {
return "misspelled " + checker.misspelled(text);
}
}
public static void main(String[] args) {
String text = "the cat sat on teh mat";
System.out.println("TightNotepad : " + new TightNotepad().check(text));
// The composition root: the one place that knows the concrete classes.
Notepad english = new Notepad(new EnglishSpellChecker());
Notepad plain = new Notepad(new NoOpSpellChecker());
Notepad test = new Notepad(t -> List.of("fake"));
System.out.println("Notepad(English) : " + english.check(text));
System.out.println("Notepad(NoOp) : " + plain.check(text));
System.out.println("Notepad(lambda for test): " + test.check(text));
}
}
TightNotepad : misspelled [teh]
Notepad(English) : misspelled [teh]
Notepad(NoOp) : misspelled []
Notepad(lambda for test): misspelled [fake]
foundTightNotepad , and it always will: the English checker is written into its field. Using another checker, or a fake in a test, means editing the class.[teh] is identical except that its constructor receives the checker. The same class producedNotepad ,[teh] and[] , depending only on what[fake] passed in.main- The lambda
is a complete test double. Becauset -> List.of("fake") is an interface with one method, a test needs no mocking library.SpellChecker
The part of main
What a container does underneath
A container needs three things: a list of definitions, a way to find the definition that matches a requested type, and a recursive step that creates each constructor argument before the object itself. This minimal container does exactly that with reflection, in about 40 lines:
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class TinyContainer {
private final List<Class<?>> definitions = new ArrayList<>();
private final Map<Class<?>, Object> singletons = new LinkedHashMap<>();
void register(Class<?> type) {
definitions.add(type);
}
<T> T getBean(Class<T> wanted) {
Class<?> type = definitions.stream()
.filter(wanted::isAssignableFrom)
.reduce((a, b) -> {
throw new IllegalStateException("two beans of type " + wanted.getSimpleName());
})
.orElseThrow(() -> new IllegalStateException(
"no bean of type " + wanted.getSimpleName()));
Object bean = singletons.get(type);
if (bean == null) {
bean = create(type);
singletons.put(type, bean);
}
return wanted.cast(bean);
}
private Object create(Class<?> type) {
try {
Constructor<?> constructor = type.getDeclaredConstructors()[0];
Class<?>[] parameterTypes = constructor.getParameterTypes();
Object[] arguments = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
arguments[i] = getBean(parameterTypes[i]); // resolve each dependency by type
}
System.out.println(" creating " + type.getSimpleName()
+ " with " + parameterTypes.length + " dependencies");
return constructor.newInstance(arguments);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
}
interface Clock {
String now();
}
static class FixedClock implements Clock {
@Override
public String now() {
return "09:30";
}
}
static class Formatter {
String format(String text, String time) {
return "[" + time + "] " + text;
}
}
static class Logger {
private final Clock clock;
private final Formatter formatter;
Logger(Clock clock, Formatter formatter) {
this.clock = clock;
this.formatter = formatter;
}
void log(String text) {
System.out.println(" " + formatter.format(text, clock.now()));
}
}
public static void main(String[] args) {
TinyContainer container = new TinyContainer();
container.register(Logger.class);
container.register(FixedClock.class);
container.register(Formatter.class);
System.out.println("Asking for a Logger:");
Logger logger = container.getBean(Logger.class);
logger.log("started");
System.out.println("Asking again returns the same object: "
+ (logger == container.getBean(Logger.class)));
System.out.println("Singletons held: " + container.singletons.keySet().stream()
.map(Class::getSimpleName).toList());
try {
container.getBean(Runnable.class);
} catch (IllegalStateException e) {
System.out.println("Missing dependency: " + e.getMessage());
}
}
}
Asking for a Logger:
creating FixedClock with 0 dependencies
creating Formatter with 0 dependencies
creating Logger with 2 dependencies
[09:30] started
Asking again returns the same object: true
Singletons held: [FixedClock, Formatter, Logger]
Missing dependency: no bean of type Runnable
- Asking for a
createdLogger andFixedClock first, thenFormatter . The container read the constructor's parameter types and resolved each one by type, recursively.Logger with 2 dependencies asked for aLogger , an interface. The container matched it toClock withFixedClock , which is how injection by type lets a class depend on an interface.isAssignableFrom- The second request returned the same object, because created beans are kept in the
map:singletons .[FixedClock, Formatter, Logger] - A type with no definition failed with
, and two matching definitions would fail too. Spring reports the same two problems asno bean of type Runnable andNoSuchBeanDefinitionException .NoUniqueBeanDefinitionException
Spring's container follows the same plan with much more around it: definitions that carry a scope, lazy flags and init methods, detection of circular dependencies, qualifiers, generics, proxies, and hooks to change definitions and beans before they are used. This container also creates beans on first request, like a plain BeanFactoryApplicationContext
The Spring container: definitions first, then beans
Spring separates reading the configuration from creating objects. First it turns @Configuration@ComponentBeanDefinitionBeanFactoryPostProcessor
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
public class SpringContainer {
interface Clock {
String now();
}
static class FixedClock implements Clock {
FixedClock() {
System.out.println(" 3. creating FixedClock");
}
@Override
public String now() {
return "09:30";
}
}
static class Logger {
private final Clock clock;
Logger(Clock clock) {
System.out.println(" 3. creating Logger");
this.clock = clock;
}
void log(String text) {
System.out.println("[" + clock.now() + "] " + text);
}
}
@Configuration
static class Config {
@Bean
static BeanFactoryPostProcessor inspector() {
return factory -> {
System.out.println(" 2. definitions read, no application bean created yet:");
for (String name : new String[] {"clock", "logger"}) {
BeanDefinition definition = factory.getBeanDefinition(name);
System.out.println(" " + name + ": scope=" + definition.getScope()
+ ", lazy=" + definition.isLazyInit()
+ ", factory method=" + definition.getFactoryMethodName());
}
};
}
@Bean
Clock clock() {
return new FixedClock();
}
@Bean
Logger logger(Clock clock) {
return new Logger(clock);
}
@EventListener
void ready(ContextRefreshedEvent event) {
System.out.println(" 4. ContextRefreshedEvent: the context is ready");
}
}
public static void main(String[] args) {
System.out.println(" 1. new AnnotationConfigApplicationContext(Config.class)");
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
context.getBean(Logger.class).log("started");
System.out.println("Bean definitions in the container:");
for (String name : context.getBeanDefinitionNames()) {
System.out.println(" " + name);
}
}
}
}
1. new AnnotationConfigApplicationContext(Config.class)
2. definitions read, no application bean created yet:
clock: scope=, lazy=false, factory method=clock
logger: scope=, lazy=false, factory method=logger
3. creating FixedClock
3. creating Logger
4. ContextRefreshedEvent: the context is ready
[09:30] started
Bean definitions in the container:
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
springContainer.Config
inspector
clock
logger
- Step 2 ran before any application bean existed. The definitions for
andclock were already there, withlogger and a factory method named after eachlazy=false method. The empty@Bean means no scope was set, which Spring treats as singleton.scope= - Step 3 created the beans,
beforeFixedClock because the logger depends on the clock. Step 4,Logger , marked the end of startup.ContextRefreshedEvent - The list of definitions holds nine names, but the configuration declared only three beans and the configuration class itself. The four
beans andinternal...Processor are registered byinternalEventListenerFactory . They are what makeAnnotationConfigApplicationContext ,@Configuration ,@Autowired and@PostConstruct work at all.@EventListener
Spring Boot's auto-configuration is built on this split: it registers definitions conditionally, depending on what is on the classpath and in the properties, before any bean is created. A BeanFactoryPostProcessor${...}static@Bean
BeanFactory and ApplicationContext
Spring has two levels of container. BeanFactoryApplicationContextReport@Autowired@PostConstruct
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class FactoryVsContext {
static class Clock {
}
static class Report {
@Autowired
Clock clock;
boolean initialized;
Report() {
System.out.println(" Report constructor runs");
}
@PostConstruct
void init() {
initialized = true;
}
String state() {
return "clock injected = " + (clock != null) + ", @PostConstruct ran = " + initialized;
}
}
public static void main(String[] args) {
System.out.println("Plain DefaultListableBeanFactory:");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("clock", new RootBeanDefinition(Clock.class));
factory.registerBeanDefinition("report", new RootBeanDefinition(Report.class));
System.out.println(" definitions registered, nothing created yet");
System.out.println(" getBean(Report):");
System.out.println(" " + factory.getBean(Report.class).state());
System.out.println("AnnotationConfigApplicationContext:");
var context = new AnnotationConfigApplicationContext();
context.register(Clock.class, Report.class);
System.out.println(" refresh():");
context.refresh();
System.out.println(" getBean(Report):");
System.out.println(" " + context.getBean(Report.class).state());
context.close();
}
}
Plain DefaultListableBeanFactory:
definitions registered, nothing created yet
getBean(Report):
Report constructor runs
clock injected = false, @PostConstruct ran = false
AnnotationConfigApplicationContext:
refresh():
Report constructor runs
getBean(Report):
clock injected = true, @PostConstruct ran = true
- The plain
created nothing untilDefaultListableBeanFactory was called. Then it built thegetBean , butReport andclock injected = false : nothing processes those annotations in a bare factory.@PostConstruct ran = false - The
created theApplicationContext duringReport , before anyone asked for it, and the annotations worked:refresh() ,clock injected = true . The context registered the annotation post-processors from the previous section automatically.@PostConstruct ran = true
| Feature | BeanFactory | ApplicationContext |
|---|---|---|
| Singletons created | On first request | At startup, so errors appear immediately |
Annotation processing (@Autowired@PostConstruct | Only if you register the post-processors | Built in |
Events (publishEvent@EventListener | No | Yes |
Environment | No | Yes |
Messages for internationalization (MessageSource | No | Yes |
Resource loading (classpath:file: | No | Yes |
Lifecycle (startstopclose | Destroy methods only | Yes |
Applications use an ApplicationContextAnnotationConfigApplicationContextGenericApplicationContextGenericXmlApplicationContextDefaultListableBeanFactory
Registering beans with code
Definitions do not have to come from annotations. Since Spring Framework 5.0, GenericApplicationContext.registerBeanSupplier
import org.springframework.context.support.GenericApplicationContext;
public class FunctionalRegistration {
record Settings(String greeting) {
}
record Greeter(Settings settings) {
Greeter {
System.out.println(" creating a Greeter with \"" + settings.greeting() + "\"");
}
String greet(String name) {
return settings.greeting() + ", " + name;
}
}
public static void main(String[] args) {
boolean formal = Boolean.parseBoolean(System.getProperty("formal", "true"));
try (var context = new GenericApplicationContext()) {
context.registerBean("settings", Settings.class,
() -> new Settings(formal ? "Good day" : "Hi"));
context.registerBean("greeter", Greeter.class,
() -> new Greeter(context.getBean(Settings.class)));
context.registerBean("lazyGreeter", Greeter.class,
() -> new Greeter(new Settings("Hello")),
definition -> definition.setLazyInit(true));
System.out.println("refresh():");
context.refresh();
System.out.println("using the beans:");
System.out.println(" " + context.getBean("greeter", Greeter.class).greet("Ana"));
System.out.println(" " + context.getBean("lazyGreeter", Greeter.class).greet("Ben"));
System.out.println("bean names: " + String.join(", ",
context.getBeanDefinitionNames()));
}
}
}
refresh():
creating a Greeter with "Good day"
using the beans:
Good day, Ana
creating a Greeter with "Hello"
Hello, Ben
bean names: settings, greeter, lazyGreeter
- During
, only one Greeter was created, the one withrefresh() . The second registration passed a customizer that set"Good day" , so its Greeter was created only whensetLazyInit(true) was first requested, just beforelazyGreeter .Hello, Ben - The greeting came from a plain Java condition on a system property. Registration is ordinary code, so it can branch, loop and read configuration without special annotations.
- The bean names are exactly the three registered.
adds no annotation processors, which keeps it small and fast to start. To use annotations in the registered beans as well, useGenericApplicationContext , which also hasAnnotationConfigApplicationContext .registerBean
Functional registration also suits libraries and tests that build a small context. Note that refresh()GenericApplicationContext
Inversion of control beyond injection
Much of Spring inverts control of the flow, not of creation. Your code supplies a small piece and the framework decides when to call it. Two common cases, a query and an event:
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;
public class CallbackInversion {
record Book(String title, int pages) {
}
record BookAdded(String title) {
}
@Component
static class Catalog {
@EventListener
void onBookAdded(BookAdded event) {
System.out.println(" listener called by Spring: indexing \"" + event.title() + "\"");
}
}
public static void main(String[] args) {
var dataSource = new DriverManagerDataSource("jdbc:h2:mem:books;DB_CLOSE_DELAY=-1");
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.execute("CREATE TABLE book (title VARCHAR(40), pages INT)");
jdbc.update("INSERT INTO book VALUES ('Dune', 412), ('Emma', 474)");
System.out.println("JdbcTemplate drives the loop and calls the RowMapper:");
List<Book> books = jdbc.query("SELECT title, pages FROM book ORDER BY title",
(row, rowNumber) -> {
System.out.println(" RowMapper called for row " + rowNumber);
return new Book(row.getString("title"), row.getInt("pages"));
});
System.out.println(" result: " + books);
System.out.println("The context delivers an event to whoever listens:");
try (var context = new AnnotationConfigApplicationContext(Catalog.class)) {
context.publishEvent(new BookAdded("Ulysses"));
}
}
}
JdbcTemplate drives the loop and calls the RowMapper:
RowMapper called for row 0
RowMapper called for row 1
result: [Book[title=Dune, pages=412], Book[title=Emma, pages=474]]
The context delivers an event to whoever listens:
listener called by Spring: indexing "Ulysses"
opened the connection, ran the query, looped over the result set and called theJdbcTemplate for rows 0 and 1. Your code only says how to turn one row into aRowMapper ; closing the connection and translating exceptions are the template's job.Book- The event was published without a reference to any listener. The context found
, matched it by the event's type, and called it. The publisher does not know who listens or how many listeners there are.Catalog.onBookAdded
The same pattern runs through the framework: TransactionTemplateRestClientDispatcherServlet
Common misunderstandings
- IoC and DI are not synonyms: dependency injection is one form of inversion of control. Events, callbacks and lifecycle hooks are others.
- Calling getBean everywhere is not injection: application code that pulls beans from the context with
uses the container as a service locator. It hides dependencies and ties the code to Spring. KeepgetBean ingetBean methods, tests and framework code.main - Not every object should be a bean: entities, request data and value objects are created by your code or by a library such as JPA or Jackson. Beans are the long-lived services that hold the application together.
- A container does not make code loosely coupled by itself: a class that depends on concrete classes, or on many collaborators, is just as tightly coupled when Spring injects them. The benefit comes from depending on small interfaces.
- Annotations are not required: Spring builds the same container from
methods, from XML or from@Bean calls. Plain classes with constructors work with all of them.registerBean
Choosing how to set up the container
| Situation | Use |
|---|---|
| A typical application | Spring Boot, which creates the right ApplicationContext |
| Plain Spring, configuration in Java | AnnotationConfigApplicationContext@Configuration |
| Beans registered from code, no annotation processing | GenericApplicationContext.registerBean |
| An existing XML configuration | GenericXmlApplicationContextClassPathXmlApplicationContext |
| Embedding a minimal container in a library | DefaultListableBeanFactory |
| A handful of classes in a small tool | Constructors and a hand-written composition root, with no container |
Whichever you choose, write classes that receive their dependencies through constructors. They then work with any container and with none. The @Configuration@Bean