The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·46

Spring Core

How Spring's container works: inversion of control and dependency injection, the ApplicationContext, bean definitions, the full bean lifecycle (instantiation, injection, post-processing, initialisation, proxying, destruction), scopes, Java configuration and component scanning, profiles, property sources and the Environment, application events, and AOP with JDK and CGLIB proxies and the self-invocation trap. Compared with Guice, Dagger, CDI, Micronaut and Quarkus build-time DI, ASP.NET Core's container, NestJS, Go's Wire and Fx, and the no-container style of Rust and Zig.

29 topics · ~26 min read · 29-question quiz
Updated Suggest a correction

Start here: letting a container build the object graph

The problem: wiring

Chapter 44's main method built the application by hand:

Java
var service = new OrderService(new InMemoryOrderRepository(), Map.of(…), maxQty);
var controller = new OrderController(service);

With five classes that's fine. With five hundred (repositories, services, clients, caches, schedulers, each needing several others), the wiring code becomes the largest and most fragile part of main, and every test, environment and configuration needs its own variant. Dependency injection (DI) keeps the principle of chapter 44 (a class receives its dependencies through its constructor rather than creating them) and hands the wiring to a container. You declare the parts; the container works out the order, creates each object once, passes each one what it needs, and calls lifecycle hooks. Spring's container is the core that everything else in the Spring ecosystem (Boot, MVC, Data, Security) builds on. The same pattern exists as ASP.NET Core's built-in DI, Dagger and Guice on the JVM, NestJS and Angular in TypeScript, and Wire and Fx in Go.

Declaring the parts

Java
interface PaymentGateway { String charge(long paise); }
@Component @Profile("!prod") static class FakeGateway implements PaymentGateway { … "FAKE charge ₹" … }
@Component @Profile("prod")  static class RazorpayGateway implements PaymentGateway { … "real charge ₹… via Razorpay" … }

interface Notifier { String send(String msg); }
@Component("sms") static class SmsNotifier implements Notifier { … }
@Component("email") @Primary static class EmailNotifier implements Notifier { … }

@Repository static class OrderRepository { … }

@Service static class OrderService {
    OrderService(OrderRepository repo, PaymentGateway payments, Notifier notifier,
                 @Qualifier("sms") Notifier sms, @Value("${cafe.gst-percent:5}") int gstPercent) { … }
    @PostConstruct void ready() { … }
    @PreDestroy void bye() { … }
}

@Configuration @ComponentScan static class AppConfig {
    @Bean Clock clock() { return () -> "2026-10-29T10:00"; }    // for classes you can't annotate
}

Each annotated class is a bean: an object the container creates and manages. @Component is the general marker; @Service, @Repository and @Controller are the same thing with a name that documents the layer. Component scanning finds them in the package. A @Configuration class with @Bean methods declares beans you build yourself, typically from third-party classes.

Running it

Java
var ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles(profile);
ctx.register(AppConfig.class); ctx.refresh();
ctx.getBean(OrderService.class).place("Masala dosa", 9000);
ctx.close();
Text
profile default:
   OrderService ready (gst 5%, gateway FakeGateway)
   FAKE charge ₹94
   email: order for Masala dosa confirmed
   SMS: your Masala dosa is being made
   beans of type Notifier: [email, sms], same OrderService each time? true
   OrderService shutting down after 1 order(s)
profile prod:                                                         (with cafe.gst-percent=18 set)
   OrderService ready (gst 18%, gateway RazorpayGateway)
   real charge ₹106 via Razorpay
   …

Read the constructor against the output to see how the container chose each argument:

  • By type. There's one OrderRepository, so it's injected. There are two PaymentGateways, but profiles switch on exactly one: the fake in development and tests, the real one in prod, with no if in the code.
  • Ambiguity resolved. Two Notifiers are always active. The plain Notifier parameter got the @Primary one (email); the parameter marked @Qualifier("sms") got the SMS one by name. With neither, startup would fail with "expected single matching bean but found 2", which is what you want: ambiguity is caught when the application starts, not when an order is placed.
  • Configuration values. @Value("${cafe.gst-percent:5}") reads a property from the environment (system properties, environment variables, application.properties, chapter 47), with 5 as the default.
  • Lifecycle. @PostConstruct ran after injection; @PreDestroy ran when the context closed (as a server does on shutdown).
  • Scope. By default each bean is a singleton: one instance for the whole application, so the same OrderService came back each time. That's why beans must be stateless or thread-safe: every request thread shares them (chapter 38).

Prefer constructor injection (as here) over annotating fields with @Autowired: dependencies are explicit, fields can be final, the class can be constructed in a plain unit test without Spring, and a constructor with ten parameters is an honest signal that the class does too much.

The other half: proxies

The container can also hand out a proxy, a generated subclass or interface implementation wrapped around your bean, which runs extra behaviour before and after your methods. That's how @Transactional, @Cacheable, @Async and @PreAuthorize work: aspect-oriented programming (AOP). It's powerful and has one famous trap, shown in the lab: a method calling another method on this bypasses the proxy, so the annotation on the second method silently does nothing.

How deep to go in Spring Core

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain DI and IoC; annotate components and use constructor injection
L2 Configure beans, qualifiers, profiles, properties, lifecycle hooks and scopes
L3 Explain the container's phases (definitions, post-processors, instantiation), proxies and AOP, events, and DI in other ecosystems
L4 Diagnose self-invocation, scope mismatches, circular dependencies, proxy and startup problems
L5 Design module boundaries and configuration for large Spring codebases; write auto-configuration
L6 Set framework conventions and upgrade strategy across many Spring services

Inversion of control

IoC and DI

Inversion of Control (IoC): instead of your code calling a library to get things done, a framework calls your code and manages the objects it needs. "Don't call us, we'll call you." Dependency injection is IoC applied to object creation: a container creates objects (beans in Spring), resolves their dependencies, and hands them over.

Java
// Without a container: every class news its dependencies (tight coupling, hard to test)
class OrderService {
    private final OrderRepository repo = new JdbcOrderRepository(new HikariDataSource(...));
}

// With DI: OrderService declares what it needs; something else decides what to supply
@Service
class OrderService {
    private final OrderRepository repo;
    private final PaymentClient payments;
    private final Clock clock;

    OrderService(OrderRepository repo, PaymentClient payments, Clock clock) {   // constructor injection
        this.repo = repo; this.payments = payments; this.clock = clock;
    }
}

Spring's container adds more than wiring:

  • lifecycle management: init and destroy callbacks, ordered shutdown;
  • scopes (one instance per app, per request, per session);
  • configuration from external sources;
  • conditional and profile-specific beans;
  • events;
  • AOP proxies that implement transactions, caching, security, async execution and retries around your beans without changing their code.

Injection styles

Style Example Verdict
Constructor injection OrderService(OrderRepository repo) Preferred. Dependencies are explicit and final, the object is fully initialised, it's testable without Spring, and circular dependencies are detected at startup. With a single constructor, no @Autowired is needed
Setter injection @Autowired void setRepo(OrderRepository r) For optional dependencies, or reconfiguration
Field injection @Autowired private OrderRepository repo; Avoid. Hides dependencies, prevents final, needs reflection or Spring in tests, and makes it easy to accumulate too many dependencies unnoticed
Java
// Optional and multiple dependencies
OrderService(OrderRepository repo,
             ObjectProvider<FraudChecker> fraud,          // lazy/optional: fraud.getIfAvailable()
             List<PricingRule> rules,                     // ALL beans of a type, ordered by @Order
             Map<String, Notifier> notifiers) { … }       // bean name → bean

The container

ApplicationContext

The BeanFactory is the core container interface: get beans by name or type, with lazy instantiation. ApplicationContext extends it with what applications need: eager singleton creation, the Environment (profiles and properties), resource loading, i18n MessageSource, application events, and automatic registration of post-processors.

Implementations:

  • AnnotationConfigApplicationContext (plain Java config);
  • AnnotationConfigServletWebServerApplicationContext (what Spring Boot creates for MVC apps);
  • the reactive web variant for WebFlux;
  • GenericApplicationContext (with functional bean registration).

Spring Boot creates and refreshes the context in SpringApplication.run() (chapter 47). The context's refresh is the startup sequence:

1 collect bean DEFINITIONS: config classes, scanning, auto-config 2 BeanFactoryPostProcessors modify definitions 3 register BeanPostProcessors (they wrap every later bean) 4 MessageSource, event multicaster · 5 create web server 6 instantiate singletons in dependency order (LIFECYCLE) 7 refreshed event; lifecycle beans start; traffic accepted definitions are recipes; beans are the objects built from them errors in steps 1–6 abort startup (missing, ambiguous, circular)
ApplicationContext refresh. Bean definitions are collected and post-processed first, then singletons are instantiated in dependency order, each passing through the bean lifecycle.

The crucial distinction is between bean definitions (metadata: class, scope, constructor arguments, dependencies, init and destroy methods, lazy flag, primary, qualifiers) and bean instances. Most of Spring's extensibility works by manipulating definitions before any bean exists (BeanFactoryPostProcessor, BeanDefinitionRegistryPostProcessor, Spring Framework 7's BeanRegistrar for programmatic registration), or by wrapping instances as they're created (BeanPostProcessor). Spring AOT (chapter 47) runs the definition phase at build time and generates code for the result.

Defining beans: configuration styles

// 1. Component scanning: stereotype annotations on your classes
@Service            // also @Component, @Repository (adds exception translation), @Controller / @RestController
class OrderService { … }

@SpringBootApplication       // = @Configuration + @EnableAutoConfiguration + @ComponentScan (this package and below)
class App { }

Resolving ambiguity

When several beans match a type, injection fails with NoUniqueBeanDefinitionException unless you resolve it:

Java
@Bean @Primary PaymentClient stripe() { … }                       // default choice
@Bean @Qualifier("fallback") PaymentClient adyen() { … }

OrderService(PaymentClient primary, @Qualifier("fallback") PaymentClient fallback) { … }

// Custom qualifier annotations read better than strings
@Qualifier @Retention(RUNTIME) @interface Fallback {}
OrderService(@Fallback PaymentClient fallback) { … }

// Conditional beans (mostly used by auto-configuration, chapter 47)
@Bean @ConditionalOnProperty(name = "shop.fraud.enabled", havingValue = "true")
FraudChecker fraudChecker() { … }
@Bean @ConditionalOnMissingBean
Clock clock() { return Clock.systemUTC(); }                        // only if the app didn't define one

Generic types act as implicit qualifiers: Repository<Order> and Repository<Customer> inject distinct beans.

Bean lifecycle and scopes

The bean lifecycle

Each singleton goes through these steps when the context starts (prototypes go through them per request for a bean, but destruction isn't managed for prototypes):

Text
bean definition
→ instantiation           constructor called (constructor injection happens HERE)
→ dependency injection     setter/field injection, @Value
→ Aware callbacks          BeanNameAware, BeanFactoryAware, ApplicationContextAware, EnvironmentAware…
→ BeanPostProcessor.postProcessBeforeInitialization   (e.g. @PostConstruct is invoked by CommonAnnotationBeanPostProcessor)
→ initialisation           @PostConstruct → InitializingBean.afterPropertiesSet() → custom init-method
→ BeanPostProcessor.postProcessAfterInitialization    ← AOP PROXIES ARE CREATED HERE
→ (bean ready; the PROXY, if any, is what gets injected elsewhere)
→ SmartLifecycle.start()   after all singletons exist (ordered by phase)
…
→ shutdown: SmartLifecycle.stop() → @PreDestroy → DisposableBean.destroy() → custom destroy-method
instantiatector populatesetters BPP beforeAware, … initPostConstr. BPP after→ proxy? readyinjected proxy (JDK or CGLIB) target bean other beans hold a reference tothe PROXY, which runs advice(tx, cache, security) then callsthe target shutdown (reverse order): stop() → @PreDestroy → destroy()
The Spring bean lifecycle. Post-processors run around initialisation; the after-initialisation hook is where AOP replaces the raw bean with a proxy, which is what other beans receive.

Practical guidance:

  • Put initialisation logic in @PostConstruct (or in the constructor, if it doesn't need proxies or other beans' initialisation). Keep it fast: slow init delays startup and readiness.
  • Work that needs the whole application (warming caches, starting consumers) belongs in ApplicationRunner/CommandLineRunner, a SmartLifecycle bean (start and stop with phases, used for message listeners), or an ApplicationReadyEvent listener.
  • Don't call @Transactional methods from @PostConstruct: the proxy may not be in place for this calls (see self-invocation below).
  • Circular dependencies: A needs B, and B needs A. With constructor injection this fails at startup, and since Spring Boot 2.6 circular references are prohibited by default even for setter injection. Treat it as a design smell: extract the shared part into a third bean, or use events. @Lazy on one injection point (which injects a lazy proxy) is a last resort.

Scopes

Scope Instances Notes
singleton (default) One per container Shared by all threads, so it must be thread-safe (stateless or safely synchronised). Most beans are singletons
prototype A new instance per lookup or injection Spring doesn't call destroy callbacks. Injecting a prototype into a singleton happens once, so you get one instance forever. Use ObjectProvider<T>/@Lookup to get fresh ones
request One per HTTP request Web contexts only
session One per HTTP session Avoid in stateless services
application One per ServletContext Rare
websocket One per WebSocket session
Custom Thread scope, refresh scope (Spring Cloud's @RefreshScope rebuilds beans on config change), job and step scope (Spring Batch)

Scoped proxies: injecting a request-scoped bean into a singleton needs a proxy that resolves the current request's instance on every call:

Java
@Component
@RequestScope                                    // = @Scope(value = "request", proxyMode = TARGET_CLASS)
class RequestContext { String tenantId; String userId; }

@Service
class ReportService {
    private final RequestContext ctx;            // actually a CGLIB proxy; each call routes to this request's instance
    ReportService(RequestContext ctx) { this.ctx = ctx; }
}
// Caveat: with virtual threads or async work, the "current request" is looked up through thread-bound
// RequestAttributes, so work handed to other threads loses it. Prefer passing context explicitly or ScopedValue.

Configuration and environment

Environment, profiles and property sources

The Environment abstraction combines two things:

  • Profiles: named, logical groups of bean definitions activated per environment (dev, test, prod, aws, local-kafka).
  • Property sources: an ordered list of key/value sources (system properties, environment variables, application.yml, profile-specific files, config servers, secret stores). The first source that defines a key wins.
Java
@Configuration
@Profile("dev")                                   // these beans exist only when 'dev' is active
class DevConfig {
    @Bean PaymentClient payments() { return new FakePaymentClient(); }
}

@Bean @Profile("!dev")                            // profile expressions: !, &, |
PaymentClient realPayments(RestClient payments) { return new HttpPaymentClient(payments); }

// Activate: spring.profiles.active=prod (property, env SPRING_PROFILES_ACTIVE, or --spring.profiles.active=prod)
// Groups (Boot): spring.profiles.group.prod=aws,postgres,kafka

Reading properties:

Java
// 1. Typed binding (preferred, chapter 47)
@ConfigurationProperties("shop.payments") record PaymentsProperties(URI baseUrl, Duration timeout) {}

// 2. @Value for single values (supports defaults and SpEL)
@Value("${shop.payments.timeout:3s}") Duration timeout;

// 3. The Environment directly (dynamic lookups)
env.getProperty("shop.feature.x", Boolean.class, false);
env.acceptsProfiles(Profiles.of("prod"));

// Custom property sources: implement an EnvironmentPostProcessor (registered in META-INF/spring.factories),
// or use spring.config.import=optional:configserver:, vault://, aws-secretsmanager:…

Profile hygiene: profiles should select infrastructure, not change business behaviour in ways that are untested. "prod uses a different pricing algorithm" means production runs code paths your tests never exercised. Prefer feature flags for behavioural switches and profiles for wiring (fakes versus real clients, local versus cloud resources).

Application events

Spring has an in-process publish/subscribe event bus for decoupling components within one application:

Java
public record OrderPlaced(String orderId, String customerId, BigDecimal total) {}   // any object can be an event

@Service
class OrderService {
    private final ApplicationEventPublisher events;
    OrderService(ApplicationEventPublisher events) { this.events = events; }

    @Transactional
    public Order place(PlaceOrder cmd) {
        var order = repo.save(Order.from(cmd));
        events.publishEvent(new OrderPlaced(order.id(), order.customerId(), order.total()));
        return order;
    }
}

@Component
class Listeners {
    @EventListener                                       // synchronous, in the publisher's thread and transaction
    void audit(OrderPlaced e) { audit.record("order.placed", e.orderId()); }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)   // only if the transaction commits
    void sendEmail(OrderPlaced e) { mailer.orderConfirmation(e.orderId()); }

    @Async @EventListener                                // asynchronous (needs @EnableAsync)
    void warmRecommendations(OrderPlaced e) { … }
}

Semantics to keep in mind:

  • @EventListener is synchronous: an exception in a listener propagates to the publisher (and can roll back its transaction).
  • @TransactionalEventListener(AFTER_COMMIT) avoids sending emails for orders that were rolled back. But if the process crashes after commit and before the listener runs, the event is lost. In-memory events aren't durable.
  • For reliable cross-service events, use the transactional outbox (chapter 51). Spring Modulith's event publication registry persists events to the database and republishes incomplete ones, bridging the two.
  • Framework events: ContextRefreshedEvent, ApplicationReadyEvent (Boot: app is ready to serve), ContextClosedEvent, AvailabilityChangeEvent (liveness and readiness, chapter 47).

Comparable mechanisms: Guava EventBus, CDI events (@Observes), MediatR notifications (.NET), NestJS EventEmitter2, Go channels or explicit observer interfaces, and Elixir Phoenix.PubSub/Registry. In-process events are simple. Durable or cross-service events need a broker.

AOP and proxies

Aspect-oriented programming

Some concerns cut across many classes: transactions, security checks, caching, retries, metrics, logging, auditing. Writing them into every method mixes them with business logic. AOP expresses them once, as aspects, and applies them at join points (in Spring: method executions on beans) selected by pointcuts:

Term Meaning
Aspect A module of cross-cutting behaviour (a class annotated with @Aspect)
Join point A point in execution where an aspect can apply. Spring AOP supports only public method execution on Spring beans (AspectJ supports many more: field access, constructors, calls)
Pointcut An expression selecting join points: execution(* com.shop..*Service.*(..)), @annotation(Audited), within(com.shop.orders..*), bean(*Repository)
Advice Code to run: @Before, @AfterReturning, @AfterThrowing, @After (finally), @Around (full control: can skip, retry, or change arguments and results)
Weaving Applying aspects. Spring: at run time via proxies. AspectJ: at compile time or load time (bytecode weaving)
Java
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
public @interface Audited { String value(); }

@Aspect
@Component
class AuditAspect {
    private final AuditLog audit;
    AuditAspect(AuditLog audit) { this.audit = audit; }

    @Around("@annotation(audited)")                                // pointcut binds the annotation
    Object around(ProceedingJoinPoint pjp, Audited audited) throws Throwable {
        long start = System.nanoTime();
        try {
            Object result = pjp.proceed();                         // call the target method
            audit.success(audited.value(), pjp.getArgs(), System.nanoTime() - start);
            return result;
        } catch (Throwable t) {
            audit.failure(audited.value(), t);
            throw t;
        }
    }
}

@Service
class OrderService {
    @Audited("order.cancel")
    public void cancel(String id) { … }
}

Spring's own features are built this way, as infrastructure aspects (advisors) applied by BeanPostProcessors: @Transactional (TransactionInterceptor), @Cacheable, @PreAuthorize (method security), @Async, @Retryable and @ConcurrencyLimit (resilience support in Spring Framework 7 core), @Validated method validation, and Micrometer's @Timed/@Observed.

Use custom aspects sparingly. Behaviour that isn't visible at the call site surprises readers, and debugging through proxies is harder. Good uses are genuinely cross-cutting technical concerns. Business logic in aspects is a smell.

Proxying: how Spring AOP works

Spring AOP creates a proxy object that implements the same type as your bean. Callers receive the proxy. Each call goes through the advice chain, then to the real target object:

Interactive diagram: What you get back is a proxy: calls in, and calls that skip it. It needs JavaScript; the text around it says the same.
Proxy type When How
JDK dynamic proxy (java.lang.reflect.Proxy) The bean implements interfaces and proxyTargetClass=false Implements the interfaces only, so you can only inject it as the interface type
CGLIB proxy (bytecode-generated subclass; Spring repackages it) Classes without interfaces, or proxyTargetClass=true (Spring Boot's default) A subclass of the bean class that overrides methods to run advice. It can't intercept final methods, private methods, or static methods, and the class itself can't be final

The consequences, which cause some of the most common Spring bugs:

1. Self-invocation bypasses the proxy. A call from one method to another on the same object (this.method()) goes directly to the target, not through the proxy, so no advice runs:

Java
@Service
class OrderService {
    public void importAll(List<Cmd> cmds) {
        for (var c : cmds) placeOne(c);           // this.placeOne(): NOT through the proxy → NO transaction!
    }

    @Transactional
    public void placeOne(Cmd c) { … }
}
controller proxy (CGLIB)TransactionInterceptorCacheInterceptor … target OrderServiceimportAll()placeOne() @Tx this.placeOne() skips the proxy: no transaction, cache or security. Fix: another bean, TransactionTemplate, or AspectJ weaving.
Self-invocation. An external call goes through the proxy and gets a transaction; an internal this-call goes straight to the target method, skipping all advice.

Fixes:

  • Move the method to another bean (usually the best design).
  • Use programmatic transactions (TransactionTemplate) for the inner unit.
  • Inject the bean's own proxy lazily (@Lazy self-injection or ObjectProvider<OrderService>), which works but is awkward.
  • Switch to AspectJ weaving (@EnableTransactionManagement(mode = AdviceMode.ASPECTJ) with compile-time or load-time weaving), which advises the bytecode itself, so self-calls work.

2. private, final and static methods aren't advised with CGLIB, so annotations on them are silently ignored. (Since Spring 6, @Transactional on protected or package-visible methods works with class-based proxies, but private still doesn't.)

3. Proxy identity and types: with JDK proxies, injecting the concrete class type fails (BeanNotOfRequiredTypeException). getClass() returns the proxy class (OrderService$$SpringCGLIB$$0); use AopUtils.getTargetClass() or ClassUtils.getUserClass().

4. Final classes: Kotlin classes are final by default, so the kotlin-spring compiler plugin (all-open) opens classes annotated with Spring stereotypes.

5. Ordering: when several aspects apply, @Order decides nesting. For example, should retries happen inside or outside the transaction? Retrying outside a transaction gets a fresh transaction per attempt, which is usually what you want.

DI and AOP in other ecosystems

Ecosystem DI Cross-cutting behaviour
Guice (Java) Runtime, module-based (bind(Repo.class).to(PgRepo.class)), lighter than Spring Method interceptors via AOP Alliance
Dagger (Java/Android) Compile-time code generation (annotation processor). No reflection; graph errors at build time None built in
Jakarta CDI (Quarkus ArC, Weld) Contexts and scopes; Quarkus resolves DI at build time Interceptors (@Interceptor, @AroundInvoke), decorators
Micronaut Compile-time DI and AOP via annotation processors (no runtime reflection or proxies generated at startup) Compile-time AOP
ASP.NET Core Built-in IServiceCollection with lifetimes Singleton / Scoped (per request) / Transient. Captive-dependency rules: don't inject Scoped into Singleton Middleware, action filters, and decorators (Scrutor). Few proxy-based interceptors
NestJS Runtime container with modules, providers, scopes (DEFAULT, REQUEST, TRANSIENT) Interceptors, guards, pipes in the request pipeline (closer to middleware than proxies)
Go Manual wiring in main(); Wire (compile-time codegen); Uber Fx/dig (runtime, reflection) Explicit decorators/middleware: wrap an interface with another implementation. No magic
Rust No conventional container: construct in main, pass Arc<State>, use trait objects or generics. Crates like shaku exist but are uncommon tower Layers, procedural macro attributes (#[tracing::instrument], #[cached]) that rewrite functions at compile time
Zig, C Explicit construction and passing (context structs, vtables, function pointers) Explicit wrapping
Python FastAPI Depends, dependency-injector library, or plain arguments Decorators (@retry, @cache, @transactional): ordinary higher-order functions applied at import time
Elixir Configuration + module parameters; behaviours (interfaces) + Mox for tests Plugs, use macros, telemetry handlers
Haskell / Scala Function arguments, the Reader monad, ZIO ZLayer, Cats Effect Resource Effect wrappers (retry, timeout combinators on effects)

Two trends stand out. Compile-time DI and AOP (Dagger, Micronaut, Quarkus, Spring AOT, Rust macros) trade some runtime dynamism for faster startup, earlier errors and native-image friendliness. And explicit composition (Go decorators, tower layers, Python decorators, effect combinators) makes cross-cutting behaviour visible at the composition site. Spring's proxy-based approach sits at the dynamic end: very powerful and largely invisible, which is both its strength and why the self-invocation and final pitfalls exist.

Lab: proxies, scopes and startup, observed

Run on JDK 21 with Spring Framework 7.0.9 (spring-context, spring-aop), using @EnableCaching with a ConcurrentMapCacheManager and @EnableAsync. Every behaviour below is one of the most common sources of "the annotation doesn't work" questions.

Experiment 1: what you actually get back

Java
@Service public static class MenuService {
    public final AtomicInteger loads = new AtomicInteger();
    @Cacheable("menu") public String menu(String day) { loads.incrementAndGet(); return "menu for " + day; }
    …
}
MenuService m = ctx.getBean(MenuService.class);
Text
bean class: Lab$MenuService$$SpringCGLIB$$0 | is a CGLIB proxy: true | reading the public field through the proxy: null

Because MenuService has an annotation that needs interception, the container returned a generated subclass (a CGLIB proxy) that holds a reference to the real MenuService and forwards calls to it, running the caching logic around them. The proxy is a separate object: its own copy of the loads field was never initialised, so reading the field through the proxy gives null. Only method calls are forwarded. Never access bean fields directly from outside; it's one more reason to keep fields private.

Experiment 2: self-invocation bypasses the proxy

Java
public String todaysMenuTwice() { return menu("monday") + " / " + menu("monday"); }   // calls this.menu()
Text
three external calls to @Cacheable menu("monday"): method body ran 1 time(s)
todaysMenuTwice() calling this.menu() twice:        method body ran 2 time(s)

From outside, the call goes through the proxy, which checks the cache: the body ran once for three calls. Inside the bean, menu(...) means this.menu(...), and this is the target, not the proxy, so the cache is never consulted. The same thing silently disables @Transactional (no transaction starts, or the wrong propagation applies), @Async, @Retryable and @PreAuthorize on methods called from the same class. Fixes, best first: move the annotated method to a separate bean; inject the bean's own proxy (@Lazy self-reference or ObjectProvider); or use AspectJ weaving, which modifies the class itself.

Experiment 3: final methods on a CGLIB proxy

Java
public int loadCount() { return loads.get(); }
public final int finalLoadCount() { return loads.get(); }
Text
loadCount() through the proxy: 2 | final finalLoadCount(): NullPointerException (Cannot invoke "java.util.concurrent.atomic.AtomicInteger.get()" because "this.loads" is null)

A subclass can't override a final method, so the proxy couldn't forward finalLoadCount: it ran on the proxy object itself, against its empty fields. The same happens with private methods and final classes (which can't be proxied at all; Kotlin classes are final by default, hence the kotlin-spring compiler plugin that opens them). Spring proxies through an interface (a JDK dynamic proxy) when told to, which avoids this but means you can only inject the interface type.

Experiment 4: @Async and the thread it runs on

Text
@Async report() called through the proxy ran on: SimpleAsyncTaskExecutor-1 | via this.report(): main (caller main)

Through the proxy, the method was handed to an executor; through this, it ran synchronously on the caller's thread, so a slow "background" job would block the request after all. In Boot, configure the executor (Boot 4 uses virtual threads when spring.threads.virtual.enabled=true), and remember that an exception in an @Async method returning void goes to an uncaught-exception handler, not to the caller.

Experiment 5: a prototype inside a singleton

Java
@Component @Scope("prototype") public static class Cart { … }
@Component public static class CheckoutA { final Cart cart; CheckoutA(Cart c) { cart = c; } }
@Component public static class CheckoutB { final ObjectProvider<Cart> carts; … Cart cart() { return carts.getObject(); } }
Text
prototype Cart injected into singleton CheckoutA: same cart on every lookup? true | via ObjectProvider in CheckoutB: carts #2, #3

A prototype-scoped bean is created fresh each time it's requested from the container, but a singleton's constructor runs once, so CheckoutA received one cart and kept it forever: every customer would share one cart. Injecting an ObjectProvider<Cart> (or Provider<Cart>, or a scoped proxy for request and session scopes) defers the lookup to each use. Scope mismatches like this are a classic source of data leaking between users.

Experiment 6: a constructor cycle

Text
constructor cycle A ↔ B: BeanCurrentlyInCreationException: Error creating bean with name 'cycle.A': Requested bean is currently
in creation: Is there an unresolvable circular reference or an asynchronous initialization dependency?

A needs a B to be constructed and B needs an A, so neither can be built. Spring Boot has refused circular references by default since 2.6, even with field injection, because a cycle usually means two classes are really one responsibility split badly, or that a third class is missing. Break it by extracting the shared logic, by publishing an application event instead of calling back, or (last resort) by injecting ObjectProvider lazily.

Experiment 7: what the container costs at startup

A generated application with 1,000 @Service classes, each tenth starting a chain of constructor dependencies:

Text
context with 1006 bean definitions refreshed in 2418 ms / 2188 ms / 2220 ms

About 2 ms per bean on this 2-core machine: scanning the classpath, parsing annotations, building definitions, resolving constructors reflectively and running post-processors. Large Spring Boot applications with several thousand beans spend seconds here, which matters for autoscaling and serverless. The remedies are covered in chapter 47: Spring AOT (definitions computed at build time), the JVM's AOT cache (chapter 39), lazy initialisation for rarely used beans, and GraalVM native images.

Try it yourself

  1. Fix experiment 2 by moving menu into a MenuCache bean injected into MenuService, and confirm the body runs once.
  2. Make MenuService implement an interface and set @EnableCaching(proxyTargetClass = false). What class does getBean return now, and what happens if you ask for MenuService.class?
  3. Add @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) to Cart. What does CheckoutA see now on each method call?
  4. Write the same OrderService wiring with Dagger (compile-time DI) or Go's Wire, and compare startup time and error messages for a missing dependency.

Revision sheet: Spring Core

Key ideas

  • IoC and DI: the framework calls your code and supplies dependencies; constructor injection preferred; depend on interfaces.
  • Container: ApplicationContext (BeanFactory plus events, resources, environment, i18n); bean definitions vs instances; BeanFactoryPostProcessor, BeanPostProcessor, BeanRegistrar (Spring 7); configuration by component scanning, @Configuration/@Bean, or functional registration.
  • Resolution: by type, then @Primary, @Qualifier, parameter name; List/Map of all candidates; ObjectProvider for optional and lazy lookups; fail fast on ambiguity.
  • Lifecycle: instantiate → inject → aware callbacks → @PostConstruct → post-processors (proxies created here) → ready → @PreDestroy; SmartLifecycle for start/stop ordering.
  • Scopes: singleton (default), prototype, request, session, application, websocket; scoped proxies.
  • Environment: property sources, profiles, @Value placeholders, @ConfigurationProperties (chapter 47); application events (@EventListener, @TransactionalEventListener).
  • AOP: advice, pointcuts, join points; Spring AOP is proxy-based (JDK dynamic proxies for interfaces, CGLIB subclasses for classes); powers @Transactional, @Cacheable, @Async, @PreAuthorize, @Retryable, @ConcurrencyLimit; AspectJ weaving for full AOP.
  • Elsewhere: ASP.NET Core DI (transient/scoped/singleton), Guice, Dagger (compile time), Micronaut and Quarkus (build-time DI), NestJS, Go Wire/Fx, Python dependency-injector, FastAPI Depends.

Numbers to remember

  • Lab: a cached method ran once for three external calls but twice for two self-calls; 1,000 beans took about 2.2 s to refresh (about 2 ms per bean).

Pitfalls

  • Self-invocation of proxied methods; annotations on private or final methods; final classes.
  • Reading fields through proxies.
  • Prototype or request-scoped beans injected into singletons.
  • Mutable state in singleton beans.
  • Field injection hiding dependencies; circular dependencies.
  • Overusing component scanning across huge packages (slow startup, surprise beans).

Glossary

  • Bean definition: metadata describing how to create a bean.
  • Post-processor: a hook that modifies definitions or instances.
  • Proxy: an object standing in for a bean to add behaviour.
  • Advice / pointcut: the extra behaviour / where it applies.
  • Profile: a named set of beans and properties for an environment.
  • Scoped proxy: a proxy that looks up the right scoped instance on each call.