Skip to content
Visual explainer 5h to learn 4 steps

Spring core: IoC, beans & dependency injection

Explain how Spring wires beans and manages their lifecycle.

By Invicly Tech, , in Backend Java Development. About 11 minutes to read.

Topic 15 of 29

In short

Spring's IoC container creates your objects, called beans, and injects their dependencies for you. Classes declare what they need, and Spring wires the graph at startup.

Think of it like this: Like a restaurant kitchen: chefs ask for ingredients and the supply team delivers them.

Explained simply

In plain Java, a class creates the objects it needs with new. An OrderService might write new PaymentClient() inside itself. That works, but now OrderService is stuck with that exact class, and testing it without calling a real payment system is hard.

Dependency injection flips this around. The class just says what it needs, usually as constructor parameters, and someone else hands those objects in. That someone is the Spring container, also called the application context.

At startup, Spring finds your classes, works out who needs what, creates every object in the right order and connects them. These managed objects are called beans. This idea, where the framework creates and wires objects instead of your code, is called Inversion of Control (IoC).

The payoff is loose coupling. You can swap a real email sender for a fake one in tests, or one payment provider for another, without touching the classes that use them. Almost every Spring feature, from transactions to security, builds on this container.

Press Play on a diagram to walk through it one step at a time.

CycleBean lifecycle (singleton)
  1. 1
    Instantiate

    Spring calls the constructor

  2. 2
    Inject dependencies

    Constructor args or setters are filled

  3. 3
    Initialise

    @PostConstruct and post-processors, proxies created

  4. 4
    In use

    Shared instance serves the whole application

  5. 5
    Destroy

    @PreDestroy runs when the context closes

  6. Back to step 1
CompareCreating dependencies vs receiving them
new inside the class
  • Class picks its own collaborators
  • Hard to swap or fake in tests
  • Hidden dependencies
  • Changes ripple to callers
Constructor injection
  • Class declares what it needs
  • Tests pass fakes with new
  • Dependencies visible in one place
  • Fields can be final

In depth

What the container does at startup

Spring Boot starts component scanning from the package of your @SpringBootApplication class and goes down through every sub-package. Classes outside that tree are not found, a common beginner surprise. For each class marked @Component (or @Service, @Repository, @Controller) and each @Bean method, Spring first records a bean definition: a recipe saying which class, which scope and which dependencies.

Then it creates the singleton beans, eagerly, in dependency order: if OrderService needs PaymentClient, PaymentClient is built first. Bean post-processors then get a chance to wrap beans in proxies, which is how @Transactional and @Cacheable work. Because all of this happens at startup, a missing or ambiguous dependency fails the application immediately with a clear message, rather than at the first request.

FlowFrom classes to a ready context
  1. 1
    Scan packages

    Find @Component classes and @Bean methods

  2. 2
    Bean definitions

    Record class, scope and dependencies

  3. 3
    Sort by dependencies

    Build what others need first

  4. 4
    Create and inject

    Call constructors with their dependencies

  5. 5
    Post-process

    @PostConstruct, then proxies for AOP features

  6. 6
    Context ready

    App starts serving

How Spring picks the right bean

Injection works by type. If a constructor needs a PaymentClient and exactly one bean of that type exists, Spring uses it. If none exists, startup fails with NoSuchBeanDefinitionException. If several exist, Spring needs a hint, otherwise you get NoUniqueBeanDefinitionException.

The hints, in practice: mark one bean @Primary to make it the default, or put @Qualifier("stripe") on the parameter to choose by name. As a last resort, Spring matches the parameter name to a bean name. You can also ask for all of them at once: a List<PaymentClient> parameter gets every implementation, and a Map<String, PaymentClient> gets them keyed by bean name, which is a neat way to build a strategy pattern. For optional dependencies, inject ObjectProvider<T> or Optional<T>.

  • One candidate: injected
  • None: NoSuchBeanDefinitionException
  • Several: @Primary, @Qualifier, or inject a List or Map

@Component, @Bean and @Configuration

Use @Component and its specialised names on classes you write. @Service and @Controller are just labels for readers and tools. @Repository adds one behaviour: database exceptions are translated into Spring's DataAccessException hierarchy.

Use @Bean methods inside a @Configuration class for objects you cannot annotate, such as a Clock, an ObjectMapper tweak or a client from a third-party library, or when creating the object needs logic. In a @Configuration class, Spring subclasses the class so that calling one @Bean method from another returns the same singleton rather than a new object. Conditional annotations such as @Profile("dev") or @ConditionalOnProperty decide whether a bean is created at all.

Scopes and why singletons must be stateless

The default scope is singleton: one instance for the whole application, shared by every thread serving every request. That is efficient, but it means a singleton must not keep per-request data in fields. A field like private User currentUser in a service will be overwritten by concurrent requests, leaking one user's data to another. Keep request data in method parameters and local variables.

Other scopes exist. prototype creates a new instance each time the bean is requested. In web apps, request and session scopes create one instance per HTTP request or user session. A trap: injecting a prototype bean into a singleton gives you only one instance, created once. To get a fresh one each time, inject ObjectProvider<MyBean> and call getObject() when you need it.

  • singleton: one per context (default)
  • prototype: new one per lookup
  • request and session: one per HTTP request or session

Lifecycle callbacks and proxies

After a bean is created and its dependencies are injected, a method annotated with @PostConstruct runs; use it for light setup like warming a small cache. When the context shuts down, @PreDestroy methods run, which is the place to close resources. Both come from jakarta.annotation.

Many Spring features work by wrapping your bean in a proxy: another object with the same type that runs extra logic before and after your method. @Transactional, @Cacheable, @Async and method security all use this. The proxy only sees calls that come from outside the bean. When one method calls another method in the same class with this, the call skips the proxy and the annotation does nothing. Since Spring Boot 2.6, circular dependencies between beans are rejected by default; treat that error as a design hint to split responsibilities.

Learn it in 4 short steps

About 1h 15m each. Track them with a timer in your plan.

  1. 1
    Learn IoC and the application context~1h 15m
  2. 2
    Define beans with @Component and @Bean~1h 15m
  3. 3
    Use constructor injection~1h 15m
  4. 4
    Understand bean scopes and lifecycle~1h 15m

Key points

  • @Component, @Service and @Repository mark classes for component scanning.
  • @Bean methods in a @Configuration class register objects you cannot annotate.
  • Prefer constructor injection: dependencies are final, explicit and easy to test.
  • Default scope is singleton: one shared instance per application context.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
@Service
public class OrderService {
  private final PaymentClient payments;

  public OrderService(PaymentClient payments) {  // constructor injection
    this.payments = payments;
  }
}

@Configuration
class AppConfig {
  @Bean
  Clock clock() { return Clock.systemUTC(); }  // third-party object as a bean
}

Choosing a payment provider at run time

You support Stripe and PayPal, and each order says which to use. Step 1: both classes implement PaymentProvider and are named beans. Step 2: inject Map<String, PaymentProvider>; Spring fills it with every implementation, keyed by bean name. Step 3: look up the provider by the order's choice and fail clearly if it is unknown. Adding a third provider is now just a new class; the router never changes.

java
interface PaymentProvider { Receipt charge(Order order); }

@Component("stripe") class StripeProvider implements PaymentProvider { /* ... */ }
@Component("paypal") class PaypalProvider implements PaymentProvider { /* ... */ }

@Service
class PaymentRouter {
  private final Map<String, PaymentProvider> providers;
  PaymentRouter(Map<String, PaymentProvider> providers) { this.providers = providers; }

  Receipt pay(Order order) {
    var p = providers.get(order.provider());
    if (p == null) throw new IllegalArgumentException("unknown provider " + order.provider());
    return p.charge(order);
  }
}

Testing time-based logic without Spring

An InvoiceService marks invoices overdue after 30 days. Calling LocalDate.now() inside would make tests depend on today's date. Step 1: register a Clock bean in a configuration class. Step 2: inject the Clock through the constructor. Step 3: in the unit test, create the service with new and a fixed clock; no Spring context starts and the test runs in milliseconds. This is the practical benefit of constructor injection.

java
@Configuration
class TimeConfig {
  @Bean Clock clock() { return Clock.systemUTC(); }
}

@Service
class InvoiceService {
  private final Clock clock;
  InvoiceService(Clock clock) { this.clock = clock; }
  boolean isOverdue(Invoice inv) {
    return inv.issued().plusDays(30).isBefore(LocalDate.now(clock));
  }
}
// Test: var fixed = Clock.fixed(Instant.parse("2026-03-01T00:00:00Z"), ZoneOffset.UTC);
//       assertTrue(new InvoiceService(fixed).isOverdue(new Invoice(LocalDate.of(2026, 1, 1))));

Quick reference

  • Component scanning starts at the package of the @SpringBootApplication class
  • One constructor needs no @Autowired; Spring uses it automatically
  • Several beans of one type: @Primary for the default, @Qualifier to choose
  • Inject List<T> or Map<String, T> to get every implementation
  • Singletons are shared across threads: no per-request state in fields
  • Use ObjectProvider<T> to get a fresh prototype bean or an optional one
  • @PostConstruct runs after injection; @PreDestroy runs on shutdown
  • Self-invocation skips proxies, so @Transactional or @Cacheable is ignored

Common mistakes

  • Field injection with @Autowired, which hides dependencies and hampers tests.
  • Storing per-request state in a singleton bean.
  • Circular dependencies between beans, a sign the design needs splitting.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Two beans implement NotificationSender and a constructor asks for one. Neither is marked. What happens?

Question 2

2A singleton service stores the current user in a field during each request. What is the risk?

Question 3

3A prototype bean is injected into a singleton's constructor. How many prototype instances does the singleton use?

Question 4

4Your new @Service class is not found at startup. It lives in com.other, while the main class is in com.shop. Why?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a GreetingService bean with a method greet(name) and use it from a CommandLineRunner bean that prints a greeting at startup.

  2. Exercise 2medium

    Create EmailSender and SmsSender, both implementing NotificationSender. Make email the default, but inject SMS into an AlertService.

  3. Exercise 3hard

    Create a request-scoped bean RequestContext holding a request id, and use it from a singleton service safely.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I still need @Autowired?
Not on a class with a single constructor; Spring has used it automatically since version 4.3. You only need @Autowired when there are several constructors and you must mark the one to use.
Why is field injection discouraged?
Fields injected by reflection cannot be final, hide how many dependencies a class has, and force tests to use Spring or reflection. Constructor injection has none of these problems.
What is the difference between @Component and @Bean?
@Component goes on your own class and is found by scanning. @Bean goes on a factory method in a @Configuration class and is used for third-party objects or objects that need custom creation logic.
Is a Spring bean thread-safe?
Not automatically. A singleton bean is shared by all threads, so it is only safe if it has no changing state, which is the normal design for services.

Go deeper

ShareXLinkedInWhatsApp