Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 9

    Beans & IoC Container

    A Spring bean is an object the ApplicationContext constructs, wires, and destroys.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    A Spring bean is an object the ApplicationContext constructs, wires, and destroys. OrderService does not choose when PricingClient is created. The context does, then hands the same singleton to every collaborator that asked for it.

    Your types use stereotypes: @Component, @Service, @Repository, @Controller. Library types use a @Bean method — RestClient, Clock, an SDK you cannot annotate. Scan starts at OrdersApplication. @Repository also translates persistence exceptions. The default bean name of OrderService is orderService.

    Scope defaults to singleton: one instance per context, safe when it is stateless. prototype is a new instance per lookup and is not destroyed for you. request and session exist only during HTTP. Injecting either into a singleton without ObjectProvider or proxyMode = TARGET_CLASS captures the first instance forever.

    Boot auto-config often sets proxyBeanMethods = false. That lite mode skips a CGLIB subclass and starts faster; a direct call from one @Bean method to another can build a second object. Take collaborators as parameters. Full @Configuration intercepts those calls and returns the container singleton.

    Purpose of this lesson

    Register Orders beans, predict scope, and follow the lifecycle through the AOP proxy so a mutable field on a singleton is an obvious cross-customer leak.

    Understanding the topic

    The context is a name-to-instance map plus a lifecycle. Business code should not call getBean.

    • Stereotype vs factory: @Service on your class; @Bean for RestClient and Clock.
    • Singleton: created at startup, cached, shared by every injection point.
    • Proxy timing: after initialization, a BeanPostProcessor may wrap the bean. @Transactional lives on that wrapper.
    • Close: @PreDestroy runs for singletons. Prototypes are your responsibility.

    Step-by-step explanation

    1. The context calls the constructor or @Bean method and injects the remaining dependencies.
    2. @PostConstruct runs, then post-processors may wrap the bean in a proxy.
    3. The singleton is cached. External calls see @Transactional; this.save() does not.
    4. On shutdown the context destroys singletons. A prototype bean is not in that list.

    Informative example

    Library types are beans. RestClient (Spring 6.1 / Boot 3.2+) is the client to reach for; RestTemplate is in maintenance. Keys are placeholders. The next lesson replaces the two strings with a record. With proxyBeanMethods = false, pass dependencies as parameters.

    java
    @Configuration(proxyBeanMethods = false)
    public class OrdersInfraConfig {
    @Bean
    Clock clock() { return Clock.systemUTC(); }
    @Bean
    RestClient stripeClient(
    @Value("${stripe.base-url}") String baseUrl,
    @Value("${stripe.api-key}") String apiKey) {
    return RestClient.builder()
    .baseUrl(baseUrl)
    .defaultHeader("Authorization", "Bearer " + apiKey)
    .build();
    }
    }

    Request scope inside a singleton needs proxyMode = TARGET_CLASS, or every call shares the first instance. Outside HTTP the scope is inactive.

    Real-world use

    TechLearningPro Orders registers OrderService with @Service, a UTC Clock, and a RestClient pointed at pricing. All three are singletons. Tests pass Clock.fixed. The audit id is request-scoped. Checkout never calls getBean; a missing collaborator fails the constructor before the first POST /api/orders. A class dropped in com.techlearningpro.common is not a bean until the scan includes it.

    Security implications

    Tomcat will share one mutable singleton across pooled threads. Scope mistakes become data leaks.

    • Set defaultHeader once, at build time. Mutating it per request attaches one customer's bearer token to the next call. Use client.mutate().
    • Scope 'request' is not active means you are outside HTTP. Promoting a token holder to a singleton is the leak.
    • A forgotten @Profile("prod") can leave a stub payment client on the live profile, or the live client on a laptop.

    Best practices

    • Keep singletons stateless. Pass the user id as a method argument.
    • Build RestClient and Clock in configuration, and inject Clock.systemUTC() in production.
    • Widen scanBasePackages only for a module that truly lives outside the application package.
    • Prefer constructor parameters over ApplicationContext.getBean in domain code.

    Common mistakes

    • A userId or cart field on a @Service. The next request sees the previous customer.
    • A prototype injected once into a singleton. Look it up per call with ObjectProvider<T>.
    • Calling another @Bean method under proxyBeanMethods = false and constructing a second client.
    • @Component above the application package: startup succeeds, then NoSuchBeanDefinitionException.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat is the difference between a bean and an object you new?+

    Answer

    The context creates, injects, optionally proxies, scopes, and destroys a bean. new skips transactions and configuration. @Service counts only when component scan sees the class. The default name of OrderService is orderService.
    2IntermediateQuestionWhen is @Bean the right registration?+

    Answer

    When you configure a type you do not own: RestClient, Clock, an SDK. Pass other beans as method parameters, especially if proxyBeanMethods is false, so you do not accidentally construct a second instance.
    3AdvancedQuestionWhen does the transactional proxy appear, and what does it miss?+

    Answer

    A post-processor wraps the bean after initialization. External calls honor @Transactional. Self-invocation does not. @PreDestroy runs for singletons on close, not for prototypes.

    Hands-on exercise

    Lab. Publish @Bean Clock clock() as Clock.systemUTC(), stamp the order with clock.instant(), and test with Clock.fixed(Instant.parse("2026-01-15T00:00:00Z"), ZoneOffset.UTC). Delete any field that remembers the caller.

    Summary

    Orders is a context of singletons: the service, a Clock, a RestClient. Register the scope you mean, refuse shared mutable fields, and let constructors describe the graph.

    Ready to mark this lesson complete?Track your journey across the entire course.