Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 66 ยท Inversion of Control and Beans

IoC and Dependency Injection

Understand inversion of control and dependency injection in Spring Boot, why constructor injection wins, and build a tiny IoC container with reflection.

Everything in Spring Boot rests on one idea: your objects do not create their collaborators, the container hands them over. A service that needs a repository does not write new JdbcRepository(); it declares the need and Spring supplies a ready object. That simple shift is called inversion of control (IoC), and the form Spring uses is dependency injection (DI).

If you want the framework-level introduction, the Advanced Java track covers dependency injection by hand and the Spring container and bean configuration. This lesson looks at the same ideas from a Spring Boot application's point of view: what the container is, the three ways to inject, why constructor injection is the standard choice, and what happens when wiring goes wrong. Spring cannot run in our sandbox, so Spring code is read-only, and a runnable mini container shows the mechanism with plain reflection.

Why dependency injection

Look at a class that builds its own dependencies:

Java
public class OrderService {
    private final OrderRepository repository = new JdbcOrderRepository("jdbc:postgresql://prod/orders");
    private final PaymentGateway gateway = new StripeGateway("sk_live_...");
}

This class cannot be tested without the real database and the real payment provider. Switching implementations means editing it. Its configuration is hard-coded. Every class that creates its own collaborators spreads such knowledge through the whole code base.

With DI the class only says what it needs:

Java
public class OrderService {
    private final OrderRepository repository;
    private final PaymentGateway gateway;

    public OrderService(OrderRepository repository, PaymentGateway gateway) {
        this.repository = repository;
        this.gateway = gateway;
    }
}

Now a unit test passes fakes, production passes real objects, and the class neither knows nor cares which. The component that decides is the container.

Who creates the objects?

Without DI Each class calls new on its own collaborators.
With DI The container builds objects and hands them in.

Your code declares needs; the container satisfies them.

1 / 2

The container and beans

In Spring, the container is the ApplicationContext. Objects it creates and manages are called beans. A bean is nothing special: an ordinary Java object that the container instantiated, wired and kept. Boot's SpringApplication.run creates the context, registers your beans (found by component scanning or declared with @Bean methods) plus the infrastructure beans from auto-configuration, then instantiates them in dependency order.

By default each bean is a singleton: one shared instance per container. Singletons must therefore be stateless or thread-safe, which is why services hold their collaborators in final fields and no per-request data.

Three ways to inject

Spring supports three injection styles. The first two TryIt examples compare them.

Java
// 1. Constructor injection (recommended)
@Service
public class OrderService {
    private final OrderRepository repository;

    public OrderService(OrderRepository repository) {
        this.repository = repository;
    }
}

// 2. Setter injection
@Service
public class ReportService {
    private Formatter formatter;

    @Autowired
    public void setFormatter(Formatter formatter) {
        this.formatter = formatter;
    }
}

// 3. Field injection (avoid)
@Service
public class MailService {
    @Autowired
    private MailSender sender;
}

Since Spring 4.3, a class with exactly one constructor needs no @Autowired at all: Spring uses that constructor. That is the pattern you will see throughout this track.

Why constructor injection wins

  1. Required dependencies are explicit. You cannot create the object without them, so no half-built object exists.
  2. final fields. The object is immutable after construction and safe to share between threads.
  3. Testable without Spring. A unit test writes new OrderService(fakeRepository). Field injection needs reflection or a Spring test context just to set a private field.
  4. Problems surface early. A missing bean fails at startup instead of with a NullPointerException in the middle of a request.
  5. Design feedback. A constructor with eight parameters shows that the class does too much, while eight @Autowired fields hide the same problem.

Setter injection fits optional dependencies that have a sensible default, and re-configuration. Field injection is shorter to type and worse in every other way; teams commonly ban it.

Java Constructor, setter and field injection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The constructor version could not even be written with a missing dependency. The other two need a second step that someone can forget.

A mini container

How does the container know what to pass? It reads the constructor's parameter types with reflection, finds or creates a bean for each type, and calls the constructor. The next TryIt builds exactly that, in about 50 lines: a registry of classes, recursive creation, singleton caching, and two of the errors you will meet in real life.

Java A tiny IoC container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the container builds the dependency graph from constructor parameter types, creates beans in dependency order, caches singletons, and fails startup when a dependency is missing or circular. What is the stand-in: the real container handles scopes, qualifiers, conditions, lifecycle callbacks, proxies for AOP and transactions, and many bean-definition sources.

Declaring beans: XML, annotations and Java config

Spring has had three ways to tell the container about a bean, and you will meet all three in real code. Here is the same two-bean application in each style.

XML (the original style, still found in older projects):

XML
<bean id="orderRepository" class="com.example.shop.JdbcOrderRepository"/>

<bean id="orderService" class="com.example.shop.OrderService">
    <constructor-arg ref="orderRepository"/>
</bean>

Annotations (component scanning finds the classes):

Java
@Repository
class JdbcOrderRepository implements OrderRepository { /* ... */ }

@Service
class OrderService {
    private final OrderRepository repository;
    OrderService(OrderRepository repository) { this.repository = repository; }
}

Java configuration (explicit factory methods, good for third-party classes):

Java
@Configuration
class ShopConfig {
    @Bean OrderRepository orderRepository() { return new JdbcOrderRepository(); }
    @Bean OrderService orderService(OrderRepository repository) { return new OrderService(repository); }
}
XML Annotations Java config
Where the wiring lives Separate file On the class In a @Configuration class
Refactoring support Weak: names are strings Strong Strong
Third-party classes Yes No (you cannot annotate them) Yes
Typical in Boot Rare (@ImportResource) Everyday Everyday, for libraries and special cases

Spring Boot applications use annotations for your own classes and Java configuration for everything else (Bean Configuration, Stereotype Annotations). The XML style is explained in XML Configuration.

Autowiring modes (the older vocabulary)

In XML, the autowire attribute chooses how the container fills dependencies without listing them:

Mode Meaning
no (default) No automatic wiring; every dependency is written with ref
byName For each setter, look for a bean whose name equals the property name
byType For each setter, look for a bean whose type matches; if two match, startup fails
constructor Like byType, but for the constructor parameters

Modern @Autowired (and a lone constructor, which needs no annotation) behaves like byType first. When several beans match, Spring narrows the choice with @Primary, @Qualifier, or finally the parameter name (Qualifiers and Injection Points). The stand-in below wires a service in the three classic ways. What is real: the matching rules and the "two candidates" failure. What is the stand-in: the registry and the reflection code.

Java Autowiring by name, by type and by constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When a second candidate appears, byType and constructor fail like Spring's NoUniqueBeanDefinitionException, while byName keeps working. That is why modern code resolves ambiguity explicitly instead of relying on names.

BeanFactory and ApplicationContext

Spring's container comes in two layers:

BeanFactory ApplicationContext
Role The basic container: creates and wires beans A BeanFactory plus enterprise features
Singleton creation Lazily, on the first getBean Eagerly at startup (wiring errors appear immediately)
Events, MessageSource (i18n), resource loading No Yes
Environment, profiles and annotation processing Manual setup Built in
Used by Almost nobody directly Every Spring Boot application

Always use an ApplicationContext; SpringApplication.run creates one for you. BeanFactory is the interface underneath it, which is why you also meet ObjectProvider and BeanFactoryAware in the beans package.

POJO, JavaBean and Spring bean

Three terms are easy to mix up, and Spring documentation uses all of them.

Term What it is Rules
POJO (plain old Java object) Any ordinary class that does not extend a framework class or implement a framework interface None. It only has to be free of framework requirements.
JavaBean A POJO that follows a convention public no-argument constructor, private fields with public getters and setters (getX/isX/setX), and usually Serializable.
Spring bean Any object the container creates and manages No class requirements at all; it can be a POJO, a record, a JavaBean or a library class. What makes it a bean is that the container owns it.

So a Spring bean is usually a POJO, but not every POJO is a bean (a new Book(...) you create yourself is not), and a JavaBean is a convention that Spring happens to understand well: property binding, @ConfigurationProperties and the older XML <property> wiring all rely on getters and setters. This is why Spring promotes writing business code as POJOs: the class stays testable with plain new, and the container is the only place that knows about Spring.

Java POJO, JavaBean and a bean registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Listing the beans of a running application

To see what the container holds, inject the context and ask it. This is handy when a bean you expected is missing, or when auto-configuration adds something you did not write:

Java
@RestController
class BeanInfoController {

    private final ApplicationContext context;

    BeanInfoController(ApplicationContext context) { this.context = context; }

    @GetMapping("/internal/beans")
    List<String> beanNames() {
        return Arrays.stream(context.getBeanDefinitionNames()).sorted().toList();
    }

    @GetMapping("/internal/beans/{name}")
    String describe(@PathVariable String name) {
        Object bean = context.getBean(name);                 // throws NoSuchBeanDefinitionException if absent
        return name + " is a " + bean.getClass().getName();
    }

    @GetMapping("/internal/payment-gateways")
    Set<String> gateways() {
        return context.getBeansOfType(PaymentGateway.class).keySet();   // name -> bean, for one type
    }
}

getBeanDefinitionNames() lists every bean name (hundreds in a Boot app, most from auto-configuration), getBean(name) or getBean(Type.class) fetches one, and getBeansOfType(Type.class) returns a map of every bean of a type. Do not expose such endpoints publicly: use them temporarily in a test or a CommandLineRunner, or rely on the Actuator beans endpoint (Actuator), which shows the same graph with each bean's type, scope and dependencies and can be secured. Setting debug=true also prints the auto-configuration report at startup.

What goes wrong, and how it reads

You will meet these three failures early; all appear in the startup log under APPLICATION FAILED TO START:

  • NoSuchBeanDefinitionException / "Parameter 0 of constructor ... required a bean of type ... that could not be found." The class you need is not a bean. Usual causes: missing stereotype annotation, wrong package (outside the scanned root), a missing starter, or a condition that switched the bean off.
  • NoUniqueBeanDefinitionException. Two beans match one type. The fix is a qualifier or a primary bean.
  • Circular dependency (A needs B, B needs A). Boot forbids it by default and fails startup with the cycle spelled out. Treat it as a design smell and break the cycle, for example by extracting a third class, instead of enabling cycles with a property.

Because the container fails fast at startup, these are cheap bugs: you see them within seconds of starting, not weeks later in production. Common Mistakes and Debugging Startup Failures collects them in one place.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does inversion of control mean in Spring?

    IoC moves the creation and wiring of collaborators out of your classes and into the container. Dependency injection is the form Spring uses.
  2. 2. Why is constructor injection preferred over field injection?

    Constructor injection makes required dependencies impossible to forget, allows immutability and needs no framework to unit test.
  3. 3. A class has exactly one constructor. Do you need @Autowired on it?

    Since Spring 4.3 a single constructor is used for injection without any annotation.
  4. 4. Two beans implement the same interface and a constructor asks for that interface. What happens by default?

    Without a qualifier or primary bean the match is ambiguous, and the container refuses to guess.

Summary

  • IoC means the container creates and wires objects; DI is the mechanism: collaborators arrive through constructors, setters or fields.
  • Objects managed by the container are beans, singletons by default, so keep them stateless.
  • Prefer constructor injection with final fields; a single constructor needs no @Autowired.
  • Setter injection suits optional dependencies; avoid field injection.
  • The container resolves constructor parameter types recursively, and startup fails fast on missing, ambiguous or circular dependencies.
  • The TryIt container is a stand-in with the same core idea as Spring's, minus scopes, conditions, proxies and lifecycle.

Next: Component Scanning and Stereotypes.