Spring Framework

Inversion of Control and Dependency Injection in Spring

Beginner8 min readReviewed by on Updated

Spring's core job is to build your object graph for you. After this guide you will understand what the IoC container is, how ApplicationContext discovers and wires beans, why constructor injection is the recommended style, how to resolve ambiguity with qualifiers, and what the XML configuration of older projects maps to in modern Java config.

What you will learn

  • Explain what inversion of control means and why a container is worth the indirection
  • Declare beans with @Configuration, @Bean and component scanning
  • Choose between constructor, setter and field injection and justify the choice
  • Resolve ambiguous dependencies with @Qualifier, @Primary and collection injection
  • Recognise XML-era configuration and translate it into Java configuration

Every non-trivial application is an object graph: a web controller needs a service, the service needs a repository, the repository needs a data source, the data source needs credentials. Someone has to build that graph, in the right order, with the right implementations for the current environment. The Spring Framework's answer is a container that owns object creation and hands each object the collaborators it declares. That single idea — inversion of control (IoC), delivered through dependency injection (DI) — is what the rest of the framework, and all of Spring Boot, is built on. This guide targets Spring Framework 6.x on Java 17 or later.

The problem the container solves

Consider a service that sends order confirmations. Without a container it creates its own collaborators:

public class OrderService {
    private final OrderRepository repository = new JdbcOrderRepository(DataSources.production());
    private final Mailer mailer = new SmtpMailer("smtp.internal", 587);

    public void confirm(long orderId) {
        Order order = repository.find(orderId);
        mailer.send(order.customerEmail(), "Order " + orderId + " confirmed");
    }
}

The class works, but it has silently made four decisions that are not its business: which repository implementation to use, where the data source comes from, which mail transport to use and how it is configured. You cannot unit-test confirm without a database and an SMTP server. You cannot swap the mailer for a queue-backed one without editing this file. Every class that follows this pattern becomes a small, hard-coded factory for its own dependencies.

Inversion of control turns the arrow around. OrderService stops looking up or building what it needs and instead declares it:

public class OrderService {
    private final OrderRepository repository;
    private final Mailer mailer;

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

    public void confirm(long orderId) { /* unchanged */ }
}

Now the class depends on two roles expressed as interfaces, and something outside it decides which concrete objects fill those roles. In a test that something is you, passing fakes. In production it is the Spring container. The class itself has no Spring import at all — that is deliberate, and a good sign.

What the container is

The container is an object that reads bean definitions — recipes describing which classes to instantiate, how to configure them and what they depend on — and uses them to build a graph of managed objects, called beans. The central interface is ApplicationContext. When you create one, it:

  1. Loads bean definitions from your configuration classes (or XML, or scanned packages).
  2. Runs bean factory post-processors that may alter definitions (property placeholder resolution, for instance).
  3. Instantiates every singleton bean, resolving each one's dependencies recursively, in dependency order.
  4. Applies bean post-processors to each new instance (this is where @PostConstruct, AOP proxies and transaction interceptors are attached).
  5. Publishes a refresh event and is then ready to serve getBean calls — though well-designed code rarely calls getBean directly.

The two implementations you will meet most often are AnnotationConfigApplicationContext for standalone or test use and AnnotationConfigWebApplicationContext (or Boot's AnnotationConfigServletWebServerApplicationContext) for web applications.

try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
    OrderService service = context.getBean(OrderService.class);
    service.confirm(42L);
}   // close() destroys singletons and runs @PreDestroy callbacks

Declaring beans with Java configuration

A configuration class is a class annotated with @Configuration whose @Bean methods each produce one bean. The method name becomes the bean name unless you override it.

@Configuration
public class AppConfig {

    @Bean
    public DataSource dataSource() {
        var ds = new HikariDataSource();
        ds.setJdbcUrl("jdbc:postgresql://db:5432/shop");
        ds.setUsername("shop");
        ds.setPassword(System.getenv("DB_PASSWORD"));
        return ds;
    }

    @Bean
    public OrderRepository orderRepository(DataSource dataSource) {   // parameter is injected
        return new JdbcOrderRepository(dataSource);
    }

    @Bean
    public Mailer mailer() {
        return new SmtpMailer("smtp.internal", 587);
    }

    @Bean
    public OrderService orderService(OrderRepository repository, Mailer mailer) {
        return new OrderService(repository, mailer);
    }
}

Method parameters are resolved by type from the container, so a @Bean method never has to call another @Bean method to obtain a dependency. It can — orderRepository(dataSource()) — and Spring will still return the single managed instance rather than a fresh object, because @Configuration classes are subclassed with CGLIB at runtime to intercept such calls. That interception is convenient but invisible, which is why passing dependencies as parameters is the clearer style.

@Bean methods shine for classes you do not own: a connection pool, a third-party client, a Clock. For your own classes, component scanning is less ceremony.

Component scanning

Annotate your classes with a stereotype annotation and tell the container which packages to scan:

@Service
public class OrderService {
    private final OrderRepository repository;
    private final Mailer mailer;

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

@Repository
public class JdbcOrderRepository implements OrderRepository { /* … */ }

@Configuration
@ComponentScan("com.example.shop")
public class AppConfig { /* only third-party beans left here */ }

@Component is the generic stereotype; @Service, @Repository, @Controller and @RestController are specialisations. Functionally they are almost identical — a scanned @Service is just a @Component — but @Repository additionally enables data-access exception translation, and the others document intent and let you filter scans. Scan the narrowest package that contains your code: scanning com or an empty string pulls in every library on the classpath that happens to use Spring stereotypes and slows startup.

The three injection styles

Spring can inject through a constructor, a setter or directly into a field. They are not interchangeable.

StyleHowProsCons
ConstructorDependencies are constructor parametersFields can be final; object is never half-built; works without Spring in tests; too many parameters is a visible design smellSlightly more typing (nothing with records/Lombok)
Setter@Autowired on a setterOptional dependencies; reconfigurable after constructionObject can exist in an invalid state; mutability
Field@Autowired on a private fieldShortestCannot be final; invisible to callers; tests need reflection or the container; hides growing dependency lists

The Spring team recommends constructor injection for mandatory dependencies and setter injection for optional ones. Field injection appears in countless tutorials because it is short, but it couples the class to a reflective container and makes plain new in a unit test impossible. With a single constructor, @Autowired is unnecessary — the container uses it implicitly.

Optional dependencies have several idioms. Pick one and be consistent:

@Service
public class ReportService {
    private final ReportStore store;
    private final Optional<AuditSink> audit;          // empty if no AuditSink bean
    private final ObjectProvider<Formatter> formatters; // lazy, may be many, may be none

    public ReportService(ReportStore store, Optional<AuditSink> audit, ObjectProvider<Formatter> formatters) {
        this.store = store;
        this.audit = audit;
        this.formatters = formatters;
    }

    void run() {
        audit.ifPresent(a -> a.record("report"));
        formatters.orderedStream().forEach(Formatter::apply);
    }
}

ObjectProvider also solves a classic problem: when a singleton needs a new prototype-scoped bean per call, provider.getObject() asks the container each time instead of holding a single stale instance.

Resolving ambiguity

Injection is by type. When two beans implement Mailer, the container cannot choose and fails at startup with NoUniqueBeanDefinitionException. You have four tools:

  • @Primary on one candidate makes it the default when nothing more specific is requested.
  • @Qualifier("smtp") at the injection point names the wanted bean (bean name, or a custom qualifier annotation you define yourself for type safety).
  • Parameter name fallback: if a parameter is named smtpMailer and a bean with that name exists, it wins — fragile, because a rename breaks wiring silently.
  • Collection injection: declare List<Mailer> or Map<String, Mailer> to receive all candidates, ordered by @Order or Ordered.
@Bean @Primary Mailer smtpMailer() { … }
@Bean Mailer queueMailer() { … }

public NotificationService(@Qualifier("queueMailer") Mailer mailer) { … }

Spring Framework 6.2 added @Fallback, the mirror image of @Primary: a bean that is chosen only when no other candidate exists — useful for library defaults that applications may override.

Generic types participate in resolution too: Repository<Order> and Repository<Customer> are distinct injection targets, so you often need no qualifier at all if your interfaces carry type parameters.

From XML to Java configuration

Older codebases, and most Spring 3/4 training material, define beans in XML:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context">
    <context:component-scan base-package="com.example.shop"/>
    <bean id="mailer" class="com.example.shop.SmtpMailer">
        <constructor-arg value="smtp.internal"/>
        <constructor-arg value="587"/>
    </bean>
    <bean id="orderService" class="com.example.shop.OrderService">
        <constructor-arg ref="orderRepository"/>
        <constructor-arg ref="mailer"/>
        <property name="retryCount" value="3"/>   <!-- setter injection -->
    </bean>
</beans>

The mapping is mechanical: <bean> becomes a @Bean method, <constructor-arg ref> becomes a method parameter, <property> becomes a setter call, <context:component-scan> becomes @ComponentScan, and <import resource> becomes @Import of another configuration class. XML is still loaded by ClassPathXmlApplicationContext and can be mixed in with @ImportResource("classpath:legacy-beans.xml"), which is the sensible path for an incremental migration. The XML era also relied on the JSR-250 @Resource and JSR-330 @Inject annotations; both still work, now from the jakarta.annotation and jakarta.inject packages, but @Autowired is the idiomatic choice.

Common mistakes

Calling getBean from application code. Passing the ApplicationContext around and looking beans up by name reintroduces the service-locator coupling DI was meant to remove. Inject what you need; if the set of beans is dynamic, inject ObjectProvider<T> or Map<String, T>.

Using new on a class that has Spring annotations. An object you construct yourself is not managed: no injection, no @Transactional, no @PostConstruct. This shows up as a NullPointerException on a field that "should have been autowired".

Scanning too broadly. @ComponentScan with no arguments scans the package of the configuration class and every sub-package. Put your root configuration at the top of your code's package hierarchy and never above it.

Mixing field injection and constructors. A class with a constructor for some dependencies and @Autowired fields for others is confusing and untestable. Move everything into the constructor.

Circular constructor dependencies. A(B) and B(A) fail at startup. Do not switch to field injection to silence the error; split the shared behaviour into a third bean or use ObjectProvider<A> for the rare legitimate late-bound case.

Two beans, no qualifier. Adding a second implementation of an interface — say a CachingProductRepository wrapping the JDBC one — breaks every existing injection point of that type. Mark the intended default with @Primary when you add the second bean.

Best practices

  • Keep domain and service classes free of Spring imports where you can. A constructor and an interface are enough; the stereotype annotation is the only Spring-specific thing they need, and even that can move to a @Bean method.
  • Prefer one constructor per class, with final fields. If a constructor grows beyond five or six parameters, the class is doing too much.
  • Use @Bean methods for third-party types and component scanning for your own.
  • Name beans deliberately when there will ever be more than one of a type, and prefer custom qualifier annotations to string names in large codebases.
  • Let startup fail fast. A missing bean discovered at boot is far cheaper than one discovered on the first request in production, so avoid @Autowired(required = false) unless the dependency is genuinely optional.

Key takeaways

  • Inversion of control means objects declare their dependencies and the container supplies them; dependency injection is the mechanism.
  • ApplicationContext reads bean definitions from @Configuration classes and scanned components, builds the singleton graph at startup and applies post-processors to every bean.
  • Constructor injection is the recommended style: immutable, testable without Spring, and honest about a class's dependencies.
  • Injection is by type; use @Primary, @Qualifier or collection injection when several beans share a type.
  • XML configuration still works and maps one-to-one onto Java configuration, which is what all new code should use.
  • Never new a Spring-managed class or call getBean in application code; both bypass the container.

Sources and further reading

Frequently asked questions

What is the difference between BeanFactory and ApplicationContext?
BeanFactory is the minimal container interface: it can create and wire beans on demand. ApplicationContext extends it with everything an application needs — eager singleton creation, event publishing, message sources for i18n, resource loading and automatic registration of post-processors. Application code should always use an ApplicationContext; BeanFactory exists for extreme footprint constraints and for framework internals.
Do I still need @Autowired on a constructor?
Not when the class has exactly one constructor. Since Spring Framework 4.3 the container uses a single constructor implicitly. You only need @Autowired to pick one constructor among several, or on setter and field injection points.
Why does Spring say a bean has a circular dependency?
Bean A needs B in its constructor and B needs A in its constructor, so neither can be created first; the container throws BeanCurrentlyInCreationException. Setter or field injection can technically break the cycle because Spring injects into a half-built singleton, but the cycle almost always signals that responsibilities are tangled. Extract the shared part into a third class instead.
Is XML configuration still supported in Spring Framework 6?
Yes. XML bean definitions, the p and c namespaces and context:component-scan still work and are fully documented. New code should use Java configuration because it is type-checked, refactoring-safe and what Spring Boot and the reference documentation assume, but an XML file can be imported into a Java configuration with @ImportResource during a migration.