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

In an ordinary program, each class is in charge of its own collaborators. A notepad that needs a spell checker writes new EnglishSpellChecker() in its constructor, and calls it when it needs it. The notepad controls which spell checker exists, when it is created and how long it lives. That control is what gets inverted.

With inversion of control (IoC), the class gives that control away. It declares that it needs a SpellChecker, and something outside it decides which one, creates it and passes it in. The same inversion applies to calls: instead of your code calling a library step by step, a framework calls your code at the right moment. This is often summed up as the Hollywood principle: "don't call us, we'll call you".

IoC is the principle; there are several ways to apply it:

Forms of inversion of control
FormWhat is invertedSpring example
Dependency injectionCreating and choosing collaboratorsConstructor parameters filled by the container
Callbacks (template method)The control flow around your codeJdbcTemplate calling your RowMapper
EventsWho calls whom@EventListener methods called when an event is published
Lifecycle callbacksWhen setup and cleanup run@PostConstruct, @PreDestroy
Service locator (the opposite of injection)Only creation; the class still asks for its collaboratorscontext.getBean(...) called from application code

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. The inverted notepad then runs with two other spell checkers that the notepad class knows nothing about:

Java
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));
    }
}
Output
TightNotepad            : misspelled [teh]
Notepad(English)        : misspelled [teh]
Notepad(NoOp)           : misspelled []
Notepad(lambda for test): misspelled [fake]
  • TightNotepad found [teh], 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.
  • Notepad is identical except that its constructor receives the checker. The same class produced [teh], [] and [fake], depending only on what main passed in.
  • The lambda t -> List.of("fake") is a complete test double. Because SpellChecker is an interface with one method, a test needs no mocking library.

The part of main that creates the objects is called the composition root: the one place that knows the concrete classes. For three classes this is fine. With hundreds of classes, writing the composition root by hand becomes a chore, and it has to get the creation order right, share the objects that should be shared, and close them at the end. That chore is what a container automates.

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:

Java
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());
        }
    }
}
Output
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 Logger created FixedClock and Formatter first, then Logger with 2 dependencies. The container read the constructor's parameter types and resolved each one by type, recursively.
  • Logger asked for a Clock, an interface. The container matched it to FixedClock with isAssignableFrom, which is how injection by type lets a class depend on an interface.
  • The second request returned the same object, because created beans are kept in the singletons map: [FixedClock, Formatter, Logger].
  • A type with no definition failed with no bean of type Runnable, and two matching definitions would fail too. Spring reports the same two problems as NoSuchBeanDefinitionException and 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 BeanFactory; an ApplicationContext creates all singletons at startup, as a later section shows.

The Spring container: definitions first, then beans

Spring separates reading the configuration from creating objects. First it turns @Configuration classes, @Component classes or XML into BeanDefinition objects. Then it lets BeanFactoryPostProcessor beans inspect or change those definitions. Only then does it create the singletons. This program prints a numbered step at each point:

Java
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);
            }
        }
    }
}
Output
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 clock and logger were already there, with lazy=false and a factory method named after each @Bean method. The empty scope= means no scope was set, which Spring treats as singleton.
  • Step 3 created the beans, FixedClock before Logger because the logger depends on the clock. Step 4, ContextRefreshedEvent, marked the end of startup.
  • The list of definitions holds nine names, but the configuration declared only three beans and the configuration class itself. The four internal...Processor beans and internalEventListenerFactory are registered by AnnotationConfigApplicationContext. They are what make @Configuration, @Autowired, @PostConstruct and @EventListener work at all.

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 is the hook that resolves ${...} placeholders in definitions, among other things. Declare it with a static @Bean method, as here, because it must exist before the other beans.

BeanFactory and ApplicationContext

Spring has two levels of container. BeanFactory is the basic one: it holds definitions and creates beans on request. ApplicationContext extends it and adds the features an application expects. The difference shows when the same two definitions are given to each. Report has an @Autowired field and a @PostConstruct method:

Java
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();
    }
}
Output
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 DefaultListableBeanFactory created nothing until getBean was called. Then it built the Report, but clock injected = false and @PostConstruct ran = false: nothing processes those annotations in a bare factory.
  • The ApplicationContext created the Report during refresh(), before anyone asked for it, and the annotations worked: clock injected = true, @PostConstruct ran = true. The context registered the annotation post-processors from the previous section automatically.
What ApplicationContext adds to BeanFactory
FeatureBeanFactoryApplicationContext
Singletons createdOn first requestAt startup, so errors appear immediately
Annotation processing (@Autowired, @PostConstruct)Only if you register the post-processorsBuilt in
Events (publishEvent, @EventListener)NoYes
Environment, profiles and property sourcesNoYes
Messages for internationalization (MessageSource)NoYes
Resource loading (classpath:, file:)NoYes
Lifecycle (start, stop, close)Destroy methods onlyYes

Applications use an ApplicationContext. The common implementations are AnnotationConfigApplicationContext for Java configuration, GenericApplicationContext for programmatic registration, GenericXmlApplicationContext for XML, and the web variants that Spring MVC and Spring Boot create. Inside each one is a DefaultListableBeanFactory that does the actual work.

Registering beans with code

Definitions do not have to come from annotations. Since Spring Framework 5.0, GenericApplicationContext.registerBean takes a Supplier that creates the bean, so a configuration can be plain code with no reflection over annotations and no classpath scanning:

Java
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()));
        }
    }
}
Output
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 refresh(), only one Greeter was created, the one with "Good day". The second registration passed a customizer that set setLazyInit(true), so its Greeter was created only when lazyGreeter was first requested, just before 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. GenericApplicationContext adds no annotation processors, which keeps it small and fast to start. To use annotations in the registered beans as well, use AnnotationConfigApplicationContext, which also has registerBean.

Functional registration also suits libraries and tests that build a small context. Note that refresh() may be called only once on a GenericApplicationContext; register everything before it.

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:

Java
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"));
        }
    }
}
Output
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"
  • JdbcTemplate opened the connection, ran the query, looped over the result set and called the RowMapper for rows 0 and 1. Your code only says how to turn one row into a Book; closing the connection and translating exceptions are the template's job.
  • The event was published without a reference to any listener. The context found Catalog.onBookAdded, matched it by the event's type, and called it. The publisher does not know who listens or how many listeners there are.

The same pattern runs through the framework: TransactionTemplate calls your lambda inside a transaction, RestClient calls your handlers for a response, and a web controller method is called by DispatcherServlet, never by you. The Spring events page covers events in depth.

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 getBean uses the container as a service locator. It hides dependencies and ties the code to Spring. Keep getBean in main methods, tests and framework code.
  • 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 @Bean methods, from XML or from registerBean calls. Plain classes with constructors work with all of them.

Choosing how to set up the container

Ways to build a Spring container
SituationUse
A typical applicationSpring Boot, which creates the right ApplicationContext for you
Plain Spring, configuration in JavaAnnotationConfigApplicationContext with @Configuration classes
Beans registered from code, no annotation processingGenericApplicationContext.registerBean
An existing XML configurationGenericXmlApplicationContext or ClassPathXmlApplicationContext
Embedding a minimal container in a libraryDefaultListableBeanFactory, knowing that annotations are not processed
A handful of classes in a small toolConstructors 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 dependency injection page covers the ways Spring supplies dependencies, Java configuration covers @Configuration and @Bean, and the first Spring application page puts it all together.