Spring IoC Lifecycle, Injection Trade-Offs, and Bean Wiring

Easy · Software Engineering Fundamentals · Java Developer · Onsite

Prompt

Your engineering team is establishing backend guidelines for Java services built on Spring Boot in a regulated trading platform. Walk through how Spring manages object wiring and justify a concrete dependency-injection standard for your team's codebase.

Address these five areas in your technical breakdown:

  1. Container startup and lifecycle ordering: Explain how ApplicationContext discovers bean definitions, instantiates managed objects, and wires collaborators, and clarify when injection runs relative to initialization callbacks such as @PostConstruct and InitializingBean.
  2. Constructor, setter, and field injection: Contrast all three wiring mechanisms across mandatory versus optional collaborators, field immutability (final), plain-Java unit testing without starting a Spring container, and safety against NullPointerException during startup.
  3. Selecting among multiple beans: Show how to control wiring when two or more beans implement the same interface, comparing @Primary, @Qualifier, and custom qualifier annotations.
  4. Scopes and concurrency: Contrast singleton (the default scope) against prototype, explain how mutable instance fields on a singleton service fail under concurrent HTTP traffic, and describe how to keep services thread-safe.
  5. Breaking circular references: Explain how mutual dependencies (BeanA needing BeanB while BeanB needs BeanA) arise, what design flaws they expose, and how to refactor the dependency graph cleanly rather than masking the cycle with @Lazy.

Scope & Expectations

  • Trace the exact bean startup timeline so it is clear why initialization callbacks can safely use injected collaborators whereas constructors cannot access @Autowired fields.
  • Provide a concrete comparison that justifies constructor injection as the default choice and defines narrow, safe patterns for optional or multi-implementation dependencies.
  • Illustrate multi-threaded state corruption on a singleton bean and show clean refactoring patterns that eliminate circular dependencies at the design level.

Step-by-step walkthrough

  1. What Inversion of Control means and what ApplicationContext does

    In plain Java without a framework, a class often constructs its own helpers using new (for example, this.pricingClient = new HttpPricingClient()). That tightly couples business logic to infrastructure: you cannot swap in a fake client for unit tests, and changing one low-level constructor forces edits across dozens of callers.

    Inversion of Control (IoC) flips that responsibility: a class only declares what collaborators it needs, and an external container creates those objects and hands them in. Dependency Injection (DI) is the mechanism of passing those collaborators into the class, and a Spring bean is simply a Java object whose creation, wiring, and cleanup are managed by Spring's container.

    In Spring, that container is the ApplicationContext. When the service starts up, ApplicationContext builds the application in four ordered phases:

    Startup of ApplicationContext
      |
      +-- 1. Discover bean definitions
      |      Scan @Component, @Service, @Repository, @Controller classes;
      |      parse @Configuration / @Bean methods and Spring Boot auto-configs.
      |      (Result: blueprints of classes, scopes, and dependencies; 0 business objects yet.)
      |
      +-- 2. Customize definitions (BeanFactoryPostProcessor)
      |      Resolve placeholders like "${pricing.url}" -> "https://quotes.internal"
      |      before any business bean is instantiated.
      |
      +-- 3. Register lifecycle hooks (BeanPostProcessor)
      |      Install processors that handle @Autowired, @PostConstruct,
      |      and Aspect-Oriented Programming (AOP) proxies such as @Transactional.
      |
      +-- 4. Instantiate and wire non-lazy singletons
             Create dependencies first (recursively), inject them, and run init hooks.
    

    Because Phase 4 wires non-lazy beans when the process boots, configuration mistakes fail at startup (NoSuchBeanDefinitionException when a required bean is missing, or NoUniqueBeanDefinitionException when two beans match ambiguously) rather than crashing on the first customer trade.

  2. Bean lifecycle: exact order of injection and initialization hooks

    For a single non-lazy singleton bean, Spring runs its lifecycle in a strict sequence:

    1. Instantiate            Java constructor runs                <-- Constructor injection happens here
    2. Populate properties    @Autowired fields & setters are set  <-- Field and setter injection happen here
    3. Aware callbacks        setBeanName, setApplicationContext
    4. Before-init hooks      @PostConstruct methods run
    5. InitializingBean       afterPropertiesSet() runs
    6. Custom init method     @Bean(initMethod = "...") runs
    7. After-init hooks       AOP proxies (@Transactional, @Async) wrap the bean
    8. Ready in service       Bean handles live traffic
    9. Container shutdown     @PreDestroy -> DisposableBean.destroy() -> destroyMethod
    

    Two practical rules follow directly from this timeline:

    1. All dependency injection finishes before any initialization hook (steps 4–6) runs. If a bean needs to warm up a cache or validate configuration using its injected collaborators, @PostConstruct is safe because both constructor and field/setter dependencies are already populated.
    2. Field and setter dependencies are still null while the constructor runs (step 1). Using an @Autowired field inside a constructor causes an immediate NullPointerException:
    @Service
    public class QuoteCache {
        @Autowired
        private PricingClient pricingClient; // Populated in step 2 (too late for constructor!)
    
        public QuoteCache() {
            // BUG: runs in step 1 while pricingClient is still null -> NullPointerException
            pricingClient.getQuote("AAPL");
        }
    
        @PostConstruct
        void warmUp() {
            // SAFE: runs in step 4 after all dependencies are injected
            pricingClient.getQuote("AAPL");
        }
    }
    

    With constructor injection, pricingClient is passed directly into QuoteCache(PricingClient pricingClient) in step 1, so the object is never observed in a half-initialized state.

    Step 7 also explains a classic Spring trap: AOP proxying wraps your bean inside a generated wrapper object that starts/commits database transactions (@Transactional) or dispatches background tasks (@Async). Other beans receive that wrapper, so external calls go through it. However, an internal self-call (this.saveOrder()) stays inside the raw object and skips the wrapper completely, so @Transactional on the inner method is silently ignored.

  3. Comparing constructor, setter, and field injection

    Spring supports three ways to wire dependencies into a bean:

    // 1. Constructor injection (recommended for all required dependencies)
    @Service
    public class OrderService {
        private final OrderRepository orderRepository;
        private final PricingClient pricingClient;
    
        // @Autowired is optional when the class has only one constructor (Spring 4.3+)
        public OrderService(OrderRepository orderRepository, PricingClient pricingClient) {
            this.orderRepository = Objects.requireNonNull(orderRepository);
            this.pricingClient = Objects.requireNonNull(pricingClient);
        }
    }
    
    // 2. Setter injection (useful only for genuinely optional or reconfigurable dependencies)
    @Service
    public class ReportService {
        private ComplianceNotifier notifier = ComplianceNotifier.NO_OP;
    
        @Autowired(required = false)
        public void setNotifier(ComplianceNotifier notifier) {
            this.notifier = notifier;
        }
    }
    
    // 3. Field injection (avoid in production code)
    @Service
    public class LegacyOrderService {
        @Autowired
        private OrderRepository orderRepository;
    }
    

    Evaluating all three styles against our four engineering criteria makes the choice clear:

    Criterion Constructor Injection Setter Injection Field Injection
    Required vs. optional Best for required dependencies: callers cannot construct the class without passing them. Optional ones can use Optional<T> or ObjectProvider<T>. Natural fit for optional dependencies (@Autowired(required = false) with a safe default like NO_OP), weak for required ones because callers can forget a setter. Poor for both: nothing in the Java type signature shows what is required or optional.
    Immutability (final) Yes. Fields can be marked private final, guaranteeing references never change after construction. No. Fields must remain mutable so setters can assign them after new. No. Java forbids final on fields set after construction.
    Unit testing without Spring Effortless. Plain JUnit calls new OrderService(mockRepo, mockPricing) in milliseconds with zero Spring context or reflection. Easy, but error-prone. Instantiate with new and remember to call every required setter in test setup. Painful. Private fields cannot be passed in; tests need reflection (ReflectionTestUtils or Mockito @InjectMocks).
    NullPointerException safety Strongest. Missing beans fail Spring startup; Objects.requireNonNull rejects null in plain Java callers too. Medium. Safe once wired, but calling new without invoking a setter leaves fields null unless given defaults. Weakest. null inside the constructor, and null whenever someone instantiates the class with new outside Spring.

    Constructor injection also acts as an early architectural warning system: if a constructor grows to 8 or 9 parameters, it is visibly doing too much and needs to be split. Field injection hides that bloat behind compact @Autowired lines.

  4. Disambiguating multiple beans of the same interface

    In trading backends, a single interface frequently has multiple active implementations—for instance, WireSettlementGateway and AchSettlementGateway both implementing SettlementGateway. If a service asks simply for SettlementGateway, Spring refuses to guess and aborts startup with NoUniqueBeanDefinitionException: expected single matching bean but found 2.

    You control selection cleanly at three levels:

    1. @Primary sets the default implementation. When most services want AchSettlementGateway, marking AchSettlementGateway with @Primary tells Spring to inject it whenever no specific qualifier is requested. (Only one bean of a type can be @Primary; marking two brings back NoUniqueBeanDefinitionException.)
    2. @Qualifier overrides the default at a specific injection point. @Qualifier filters the candidates before @Primary is considered, so @Qualifier always wins over @Primary.
    3. Custom qualifier annotations prevent string typos. @Qualifier("wireSettlementGateway") uses a raw string that can be misspelled ("wrieSettlementGateway" only fails when the context boots). Meta-annotating your own annotation with @Qualifier gives compile-time safety and IDE refactoring support:
    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE, ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
    public @interface HighValueWire { }
    
    @Component
    @Primary
    public class AchSettlementGateway implements SettlementGateway { }
    
    @Component
    @HighValueWire
    public class WireSettlementGateway implements SettlementGateway { }
    
    @Service
    public class InstitutionalTransferService {
        private final SettlementGateway gateway;
    
        // Explicitly selects WireSettlementGateway, overriding AchSettlementGateway's @Primary
        public InstitutionalTransferService(@HighValueWire SettlementGateway gateway) {
            this.gateway = gateway;
        }
    }
    

    Avoid relying on Spring's last-resort parameter-name fallback (naming the constructor parameter achSettlementGateway without @Qualifier), because a harmless variable rename silently changes wiring or breaks startup.

    When the right implementation depends on runtime request data (such as transfer amount or rail) or all implementations should run (such as fan-out notifications), inject a collection or map instead: - List<ComplianceNotifier> injects every ComplianceNotifier bean (ordered by @Order), letting you loop over all listeners cleanly. - Map<String, SettlementGateway> injects all gateways keyed by bean name, letting a router look up the right rail per request without a brittle if/else chain.

  5. Bean scopes and a worked thread-safety failure

    A bean scope defines how many instances Spring creates and how long they live:

    • singleton (the default): Spring creates one instance per ApplicationContext at startup and shares that exact object across every caller and every HTTP request thread. Spring Boot's embedded Tomcat runs up to 200 concurrent worker threads by default (server.tomcat.threads.max=200).
    • prototype: Spring creates a brand-new instance each time the container resolves the bean (each injection point or ObjectProvider.getObject() call). Spring runs initialization hooks on the new object and then hands over ownership—it does not retain a reference and does not call @PreDestroy on shutdown.
    • Web-aware contexts also provide request, session, and application scopes bound to HTTP lifecycles.

    Storing per-request mutable fields on a singleton service causes subtle data-corruption race conditions under concurrent load:

    @Service // Singleton by default: ONE instance shared by all 200 HTTP threads!
    public class ExecutionService {
        private final PricingClient pricingClient;
        private int executedCount = 100;    // BUG 1: unsynchronized shared counter
        private BigDecimal currentQuote;    // BUG 2: per-request price stored on shared field
    
        public ExecutionService(PricingClient pricingClient) {
            this.pricingClient = pricingClient;
        }
    
        public BigDecimal executeMarketBuy(String ticker, int shares) {
            executedCount++; // Read -> add 1 -> write (3 separate CPU steps, NOT atomic!)
            currentQuote = pricingClient.getQuote(ticker);
            return currentQuote.multiply(BigDecimal.valueOf(shares));
        }
    }
    

    Walk through two simultaneous orders—Thread A buying 100 shares of AAPL ($185.50) and Thread B buying 100 shares of PENNY ($1.20):

    Time   Thread A (100 AAPL @ $185.50)              Thread B (100 PENNY @ $1.20)          Shared singleton state
    ----   -----------------------------------------  ------------------------------------  ----------------------
    t0                                                                                      executedCount = 100
    t1     reads executedCount (100)                  reads executedCount (100)             executedCount = 100
    t2     writes 100 + 1 = 101                       writes 100 + 1 = 101                  executedCount = 101 (1 lost!)
    t3     currentQuote = $185.50                                                           currentQuote = 185.50
    t4     (context switch before multiply)           currentQuote = $1.20                  currentQuote = 1.20
    t5     computes $1.20 * 100 = $120.00!            computes $1.20 * 100 = $120.00        AAPL filled $18,430 wrong!
    

    Two orders executed, yet executedCount rose from 100 to 101, and Alice's AAPL trade was priced at $120.00 instead of $18,550.00. Worse, single-threaded unit tests never catch this!

    How to design thread-safe stateless services: - Keep all request-specific values (currentQuote, order, accountId) in method parameters and local variables, which live privately on each thread's call stack. - Mark injected dependencies private final and verify collaborators themselves are thread-safe (for example, use immutable DateTimeFormatter instead of mutable SimpleDateFormat). - If a service genuinely needs an in-memory counter or cache, use concurrent data structures (AtomicLong, LongAdder, ConcurrentHashMap), and store durable business state in the database or Redis.

  6. Circular dependencies: why they happen and how to refactor

    A circular dependency occurs when BeanA requires BeanB to be constructed, and BeanB requires BeanA (directly or through a longer chain A -> B -> C -> A):

    OrderService   ---needs--->  AccountService   (checks buying power before placing an order)
    AccountService ---needs--->  OrderService     (sums open orders to calculate buying power)
    

    With constructor injection, Spring starts instantiating OrderService, pauses to instantiate AccountService, sees AccountService asking for OrderService while OrderService is still mid-construction, and aborts startup with BeanCurrentlyInCreationException.

    A cycle is almost always an architectural smell: - Single Responsibility Principle (SRP) violation: two classes share an unextracted concept ("open-order exposure" belongs neither purely to order placement nor purely to account profile management). - Broken layering: neither service sits cleanly above the other, so neither can be understood or unit-tested on its own.

    Instead of slapping @Lazy onto a constructor parameter—which injects a stand-in proxy so startup succeeds, hiding the cycle until runtime and delaying wiring errors until the first live call—fix the dependency graph directly:

    1. Extract a third focused service (most common fix): move the shared calculation into BuyingPowerCalculator (or read directly from OpenOrderRepository) so all arrows point strictly downward:
    OrderService ---> BuyingPowerCalculator <--- AccountService
                               |
                               v
                      OpenOrderRepository
    
    1. Invert one direction with domain events: OrderService depends on AccountService to check buying power, then publishes an OrderPlacedEvent via ApplicationEventPublisher (handled with @TransactionalEventListener after commit) if AccountService needs to react asynchronously without importing OrderService.
    2. Pass computed data as a method parameter: have the higher-level caller fetch open-order totals first and pass the BigDecimal value into accountService.hasBuyingPower(accountId, openExposure).
  7. Summary: architectural standard for Spring microservices

    Putting all five areas together gives a concise, enforceable team standard:

    • Constructor injection with private final fields for every required collaborator; never use field injection in production classes.
    • Explicit optionality via ObjectProvider<T>, Optional<T>, or @Autowired(required = false) setters with safe non-null defaults.
    • @Primary + custom @Qualifier annotations (or List<T> / Map<String, T> for dynamic routing) whenever an interface has multiple beans; never rely on variable-name matching.
    • Stateless singleton services where per-request data stays on the stack and shared state uses thread-safe primitives or external data stores.
    • Zero circular dependencies, keeping Spring Boot's strict startup check enabled and breaking cycles by extracting shared services or publishing events rather than masking them with @Lazy.
    • Plain JUnit constructor tests for business logic (new OrderService(mockRepo, mockPricing)), reserving Spring context slices for web and database boundaries.

Intuition & how it works

Think of a Spring application like a busy restaurant kitchen preparing to open for dinner. Without Dependency Injection (DI)—a pattern where objects receive their helpers from the outside instead of building them internally—every chef would walk in and build their own stove, refrigerator, and card reader from scratch using new. With Inversion of Control (IoC)—handing object creation and wiring over to a framework container—Spring's ApplicationContext acts as the operations manager: before the doors open to customers, it reads every station's blueprint, builds shared equipment once, verifies nothing is missing, and hands each chef the exact tools listed on their constructor.

Creating collaborators manually with new inside services hardcodes real network clients and databases into business logic, making fast unit tests impossible. Meanwhile, scattering @Autowired on private fields hides what a class depends on, prevents final fields, leaves fields null inside the constructor, and forces tests to use reflection just to set up an object. Constructor injection solves both problems at once: the compiler enforces required inputs, fields stay final, and Spring verifies the entire graph at startup.

Walk through a tiny concrete startup trace with 3 beans—OrderRepository, AchSettlementGateway (@Primary), and WireSettlementGateway (@HighValueWire)—wired into OrderService(OrderRepository repo, SettlementGateway gateway): 1. Scan blueprints: ApplicationContext discovers all four classes and records their types and qualifiers without running any constructors yet. 2. Resolve dependencies first: To create OrderService, Spring checks OrderRepository (1 match) and SettlementGateway (2 matches, narrowed to AchSettlementGateway because it is marked @Primary and no @Qualifier overrode it). 3. Construct in dependency order: Spring instantiates OrderRepository and AchSettlementGateway, then calls new OrderService(orderRepository, achSettlementGateway) so OrderService's final fields are non-null from birth. 4. Run init hooks & wrap proxies: Spring runs any @PostConstruct method on OrderService, wraps it in an AOP proxy (a generated wrapper that intercepts calls for cross-cutting concerns like @Transactional), and registers the single shared instance to serve incoming requests.

Key points

  • ApplicationContext fails fast at startup: It discovers bean definitions (metadata blueprints for managed objects), resolves configuration placeholders via BeanFactoryPostProcessor, registers lifecycle hooks via BeanPostProcessor, and instantiates non-lazy singletons (beans with exactly one shared instance per container) before accepting traffic.
  • Injection precedes initialization hooks: Constructor injection happens during instantiation (step 1), field and setter injection happen right after (step 2), and initialization callbacks (@PostConstruct, InitializingBean.afterPropertiesSet(), custom initMethod) run only after all dependencies are populated (steps 4–6), followed by proxy wrapping (step 7).
  • Constructor injection is the production default: Required dependencies are explicit constructor parameters stored in immutable (final, unchangeable after construction) fields, enabling millisecond plain-Java unit tests (new OrderService(mockRepo, mockGateway)) and eliminating half-initialized objects.
  • Disambiguation follows a clear precedence: @Qualifier (best written as a custom compile-time annotation) narrows candidates first and overrides @Primary; @Primary chooses the default when no qualifier is given; List<T> or Map<String, T> handles multi-sink fan-out or runtime routing cleanly.
  • Singleton beans must be stateless: Because up to 200 HTTP worker threads share one singleton instance by default in Spring Boot's embedded Tomcat, per-request data belongs in local variables on each thread's stack, never in mutable instance fields. A prototype bean creates a fresh instance per container lookup, and Spring does not call its @PreDestroy hook.
  • Circular dependencies signal an architectural smell: When BeanA and BeanB depend on each other, extract the shared responsibility into a third class, invert one direction with events, or pass computed values as method arguments instead of hiding the cycle behind @Lazy.

Common mistakes

  • Accessing an @Autowired field inside the constructor: Field injection runs after the constructor returns, so the field is guaranteed to be null inside the constructor and throws NullPointerException.
  • Calling new SomeService() manually in production code: Objects created with new bypass the Spring container completely—their @Autowired dependencies remain null and annotations like @Transactional or @Async silently do nothing.
  • Self-invocation of @Transactional or @Async methods: Calling this.processBatch() from another method inside the same class bypasses Spring's outer proxy wrapper, so no transaction starts and no async thread is spawned.
  • Storing per-request fields or SimpleDateFormat on a singleton service: Concurrent threads overwrite each other's values (a race condition, where output depends on unpredictable thread timing), causing lost counter updates or cross-account data leaks that single-threaded tests never catch.
  • Expecting a prototype bean injected directly into a singleton to refresh per request: Direct injection runs once when the singleton is created, permanently freezing that single prototype instance inside the singleton.
  • Marking two implementations of the same interface @Primary or relying on variable names: Two @Primary beans crash startup with NoUniqueBeanDefinitionException, while relying on parameter-name matching silently breaks when someone renames a parameter during refactoring.
  • Masking circular dependencies with @Lazy or allow-circular-references=true: This leaves tight coupling intact and pushes wiring failures from predictable startup checks to live production traffic.

Follow-up questions

  • What happens when a singleton service injects a prototype-scoped bean directly, and how can you obtain a fresh prototype instance per call using ObjectProvider or @Lookup? When a singleton injects a prototype directly via its constructor, Spring resolves the dependency once at startup, so the singleton reuses that exact same prototype instance forever. The cleanest modern fix is injecting ObjectProvider<MyPrototype> (or jakarta.inject.Provider<MyPrototype>) into the singleton's constructor and calling provider.getObject() inside the method whenever a fresh instance is needed—this is explicit, type-safe, and easy to mock in unit tests. Alternatively, @Lookup on an abstract or dummy getter tells Spring to subclass the singleton via CGLIB and override that getter to fetch a new bean from the container, though @Lookup cannot be used on final classes or beans created via @Bean methods. A third option, @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS), injects a proxy that fetches a brand-new prototype on every individual method call, which is dangerous if two consecutive method calls on the variable expect to share temporary builder state.
  • In what situations would you register beans via @Configuration and @Bean methods rather than relying on @Component or @Service scanning? Use @Configuration and @Bean whenever you do not own the source code to add @Component (such as configuring third-party SDK clients, DataSource, RestClient, or Jackson's ObjectMapper), when object construction requires custom builder logic or timeout wiring, or when you need to register multiple beans of the same class with different configurations and qualifiers (such as primary and backup market-data HTTP clients). Explicit @Bean methods are also great when keeping core domain classes completely free of Spring annotations or conditionally wiring beans with @ConditionalOnProperty and @Profile. Use component scanning (@Service, @Repository, @Controller) for your own standard application classes where constructor wiring needs zero custom setup code.
  • What is Spring Boot's default behavior for circular bean references from version 2.6 onward, and why did the framework adopt that policy? Starting in Spring Boot 2.6, spring.main.allow-circular-references defaults to false, causing any dependency cycle—even field- or setter-injected singleton cycles that older versions quietly resolved via early half-constructed object references—to fail fast at startup with a clear cycle diagram. The Spring team made this change because circular dependencies almost always indicate tangled responsibilities, and resolving them via early references risks exposing partially initialized beans before their own dependencies or @PostConstruct logic have run. Early raw references can also clash fatally with post-processors like @Async that wrap the bean in a proxy later in initialization, so rejecting cycles immediately pushes teams to keep clean, acyclic service layers.

Follow-up questions

Similar questions

More Schwab interview questions

All 2 Schwab questions →