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:
- Container startup and lifecycle ordering: Explain how
ApplicationContextdiscovers bean definitions, instantiates managed objects, and wires collaborators, and clarify when injection runs relative to initialization callbacks such as@PostConstructandInitializingBean. - 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 againstNullPointerExceptionduring startup. - 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. - Scopes and concurrency: Contrast
singleton(the default scope) againstprototype, explain how mutable instance fields on a singleton service fail under concurrent HTTP traffic, and describe how to keep services thread-safe. - Breaking circular references: Explain how mutual dependencies (
BeanAneedingBeanBwhileBeanBneedsBeanA) 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
@Autowiredfields. - 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
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,ApplicationContextbuilds 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 (
NoSuchBeanDefinitionExceptionwhen a required bean is missing, orNoUniqueBeanDefinitionExceptionwhen two beans match ambiguously) rather than crashing on the first customer trade.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() -> destroyMethodTwo practical rules follow directly from this timeline:
- 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,
@PostConstructis safe because both constructor and field/setter dependencies are already populated. - Field and setter dependencies are still
nullwhile the constructor runs (step 1). Using an@Autowiredfield inside a constructor causes an immediateNullPointerException:
@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,
pricingClientis passed directly intoQuoteCache(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@Transactionalon the inner method is silently ignored.- 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,
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>orObjectProvider<T>.Natural fit for optional dependencies ( @Autowired(required = false)with a safe default likeNO_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 finalon 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 newand remember to call every required setter in test setup.Painful. Private fields cannot be passed in; tests need reflection ( ReflectionTestUtilsor Mockito@InjectMocks).NullPointerExceptionsafetyStrongest. Missing beans fail Spring startup; Objects.requireNonNullrejectsnullin plain Java callers too.Medium. Safe once wired, but calling newwithout invoking a setter leaves fieldsnullunless given defaults.Weakest. nullinside the constructor, andnullwhenever someone instantiates the class withnewoutside 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
@Autowiredlines.Disambiguating multiple beans of the same interface
In trading backends, a single interface frequently has multiple active implementations—for instance,
WireSettlementGatewayandAchSettlementGatewayboth implementingSettlementGateway. If a service asks simply forSettlementGateway, Spring refuses to guess and aborts startup withNoUniqueBeanDefinitionException: expected single matching bean but found 2.You control selection cleanly at three levels:
@Primarysets the default implementation. When most services wantAchSettlementGateway, markingAchSettlementGatewaywith@Primarytells Spring to inject it whenever no specific qualifier is requested. (Only one bean of a type can be@Primary; marking two brings backNoUniqueBeanDefinitionException.)@Qualifieroverrides the default at a specific injection point.@Qualifierfilters the candidates before@Primaryis considered, so@Qualifieralways wins over@Primary.- 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@Qualifiergives 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
achSettlementGatewaywithout@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 everyComplianceNotifierbean (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 brittleif/elsechain.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 perApplicationContextat 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 orObjectProvider.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@PreDestroyon shutdown.- Web-aware contexts also provide
request,session, andapplicationscopes bound to HTTP lifecycles.
Storing per-request mutable fields on a
singletonservice 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 ofPENNY($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
executedCountrose from100to101, and Alice'sAAPLtrade was priced at$120.00instead 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 dependenciesprivate finaland verify collaborators themselves are thread-safe (for example, use immutableDateTimeFormatterinstead of mutableSimpleDateFormat). - 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.Circular dependencies: why they happen and how to refactor
A circular dependency occurs when
BeanArequiresBeanBto be constructed, andBeanBrequiresBeanA(directly or through a longer chainA -> 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 instantiateAccountService, seesAccountServiceasking forOrderServicewhileOrderServiceis still mid-construction, and aborts startup withBeanCurrentlyInCreationException.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
@Lazyonto 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:- Extract a third focused service (most common fix): move the shared calculation into
BuyingPowerCalculator(or read directly fromOpenOrderRepository) so all arrows point strictly downward:
OrderService ---> BuyingPowerCalculator <--- AccountService | v OpenOrderRepository- Invert one direction with domain events:
OrderServicedepends onAccountServiceto check buying power, then publishes anOrderPlacedEventviaApplicationEventPublisher(handled with@TransactionalEventListenerafter commit) ifAccountServiceneeds to react asynchronously without importingOrderService. - Pass computed data as a method parameter: have the higher-level caller fetch open-order totals first and pass the
BigDecimalvalue intoaccountService.hasBuyingPower(accountId, openExposure).
- Extract a third focused service (most common fix): move the shared calculation into
Summary: architectural standard for Spring microservices
Putting all five areas together gives a concise, enforceable team standard:
- Constructor injection with
private finalfields 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@Qualifierannotations (orList<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.
- Constructor injection with
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
ApplicationContextfails fast at startup: It discovers bean definitions (metadata blueprints for managed objects), resolves configuration placeholders viaBeanFactoryPostProcessor, registers lifecycle hooks viaBeanPostProcessor, 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(), custominitMethod) 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;@Primarychooses the default when no qualifier is given;List<T>orMap<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
@PreDestroyhook. - Circular dependencies signal an architectural smell: When
BeanAandBeanBdepend 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
@Autowiredfield inside the constructor: Field injection runs after the constructor returns, so the field is guaranteed to benullinside the constructor and throwsNullPointerException. - Calling
new SomeService()manually in production code: Objects created withnewbypass the Spring container completely—their@Autowireddependencies remainnulland annotations like@Transactionalor@Asyncsilently do nothing. - Self-invocation of
@Transactionalor@Asyncmethods: Callingthis.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
SimpleDateFormaton 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
prototypebean injected directly into asingletonto 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
@Primaryor relying on variable names: Two@Primarybeans crash startup withNoUniqueBeanDefinitionException, while relying on parameter-name matching silently breaks when someone renames a parameter during refactoring. - Masking circular dependencies with
@Lazyorallow-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
ObjectProvideror@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 injectingObjectProvider<MyPrototype>(orjakarta.inject.Provider<MyPrototype>) into the singleton's constructor and callingprovider.getObject()inside the method whenever a fresh instance is needed—this is explicit, type-safe, and easy to mock in unit tests. Alternatively,@Lookupon 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@Lookupcannot be used onfinalclasses or beans created via@Beanmethods. 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
@Configurationand@Beanmethods rather than relying on@Componentor@Servicescanning? Use@Configurationand@Beanwhenever you do not own the source code to add@Component(such as configuring third-party SDK clients,DataSource,RestClient, or Jackson'sObjectMapper), 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@Beanmethods are also great when keeping core domain classes completely free of Spring annotations or conditionally wiring beans with@ConditionalOnPropertyand@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-referencesdefaults tofalse, 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@PostConstructlogic have run. Early raw references can also clash fatally with post-processors like@Asyncthat wrap the bean in a proxy later in initialization, so rejecting cycles immediately pushes teams to keep clean, acyclic service layers.
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`?
- In what situations would you register beans via `@Configuration` and `@Bean` methods rather than relying on `@Component` or `@Service` scanning?
- What is Spring Boot's default behavior for circular bean references from version 2.6 onward, and why did the framework adopt that policy?
Similar questions
- Auditing and Refactoring a Flawed Spring Boot Order Controller
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager