Workbench / Volume 3 Exercises: The Backend
V3·46
Spring Core
Exercises for Volume 3, chapter 46: inversion of control and dependency injection; injection styles; the ApplicationContext and configuration styles; resolving ambiguity; the bean lifecycle and scopes; the Environment, profiles and property sources; application events; aspect-oriented programming and how Spring's proxies work; and DI and AOP in other ecosystems. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
The four sets and the locking work as before. The code is Java 21 with Spring Framework 7.0 (spring-context, spring-beans, spring-aop), and no Spring Boot, so you can see what the core container does on its own. Every quoted output is real, and six of them catch experienced developers:
- P1. With two
PaymentGatewaybeans, startup failed withNoUniqueBeanDefinitionException: … expected single matching bean but found 2: razorpay,cashfree. An ordered stream returned them in@Orderorder,[cashfree, razorpay], not in registration order. - P2. The full lifecycle printed in order: constructor → setter injection → BPP before init →
@PostConstruct→afterPropertiesSet→initMethod→ BPP after init →SmartLifecycle.start→ContextRefreshedEvent→SmartLifecycle.stop→@PreDestroy→DisposableBean.destroy. - P3. Calling a
@Beanmethod twice inside a@Configurationclass returned the same instance, because the configuration class itself was a CGLIB proxy (Full$$SpringCGLIB$$0). WithproxyBeanMethods = false, it returned two different instances. - P4. A listener that threw made
publishEventthrow to the publisher, and the listener after it never ran. The log showed[sms on main, loyalty], and all of it ran on the publisher's thread. - P5. A plain
AnnotationConfigApplicationContextinjected a missing property as the literal string${tiffinbox.db.url}. Only with aPropertySourcesPlaceholderConfigurer(which Boot always registers) did it fail withCould not resolve placeholder. - P6. An interface-based proxy was a
jdk.proxy2.$Proxy19that was not aninstanceof Razorpay. A class-based proxy wasRazorpay$$SpringCGLIB$$0and was one.
The chapter's lab already measured these, so the exercises build on them rather than repeat them:
- the CGLIB proxy whose public field read
null; - self-invocation bypassing
@Cacheable(2 runs instead of 1); finalmethods hitting an NPE on the proxy;@Asyncviathisrunning onmain;- a prototype stuck inside a singleton;
- constructor cycles;
- about 2 ms per bean at startup (1,006 beans in about 2.2 s).
Coverage map.
| Chapter component | Exercises |
|---|---|
| IoC and DI; injection styles | T1, P7 |
| ApplicationContext; configuration styles | T2, P3 |
| resolving ambiguity | T3, P1 |
| bean lifecycle | T4, P2 |
| scopes | T5, P8 |
| Environment, profiles, property sources | T6, P5 |
| application events | T7, P4 |
| AOP concepts; proxying | T8, P6 |
| DI and AOP in other ecosystems | T9, P9 |
Theory
T1. Inversion of control, DI and injection styles
- Explain inversion of control in general (frameworks call your code; "don't call us, we'll call you") and dependency injection as one form of it. How does Spring's container differ from ch44's manual composition root? What does it gain: lifecycle, scopes, proxies, configuration, conditional wiring. What does it lose: compile-time safety, explicitness, startup time (the lab's 2 ms per bean)?
- Compare injection styles in Spring:
- constructor (single constructor, no annotation needed;
finalfields; fails fast); - setter (optional dependencies, cycles allowed); - field (@Autowiredon fields: hidden, untestable without reflection); - method injection (@Lookup,ObjectProvider).
Which are acceptable in production code, and why does the Spring team recommend constructors?
3. What does "the application shouldn't know the container exists" mean? Give examples of container leakage: ApplicationContextAware, getBean calls, @Autowired in domain classes, and static SpringContext.getBean() helpers. How do you keep domain code free of Spring (ch43's module boundaries)?
T2. The ApplicationContext and configuration styles
- Describe what
ApplicationContext.refresh()does: - load bean definitions (component scanning,
@Configurationparsing,@Import); - run
BeanFactoryPostProcessors (placeholders: P5); - register
BeanPostProcessors; - instantiate the singletons (constructor resolution, injection, initialisation);
- publish
ContextRefreshedEvent; - start the
SmartLifecyclebeans (P2's order showsstartbefore the refreshed event).
Where does the lab's 2 ms per bean go?
2. Compare the configuration styles:
- component scanning (@Component, @Service and friends);
- Java configuration (@Configuration plus @Bean methods);
- functional registration (registerBean(…), BeanRegistrar in Spring 7);
- XML (legacy).
When should each be used? Why are @Bean methods best for wiring third-party classes and for keeping Spring out of domain classes?
3. P3: @Configuration classes are proxied (Full$$SpringCGLIB$$0), so calling counter() twice returns the singleton bean (same instance, equal to the context's bean). With proxyBeanMethods = false (lite mode), each call creates a new object. Explain why Spring Boot's own auto-configurations use proxyBeanMethods = false, and the bug when someone calls a @Bean method directly in lite mode.
T3. Resolving ambiguity
- P1: two beans implementing
PaymentGatewaymade injection fail withNoUniqueBeanDefinitionException … found 2: razorpay,cashfree. List the resolution tools: -@Primary; -@Qualifier("razorpay")or custom qualifier annotations (@Gateway(Provider.RAZORPAY)); - parameter names matching bean names (with-parameters); -@Fallback(Spring 6.2+); - injectingList<PaymentGateway>,Map<String, PaymentGateway>orObjectProvider<PaymentGateway>. - Ordering. P1's
orderedStream()returned[cashfree, razorpay]from@Order(1)/@Order(2), whilegetBeansOfTypekept registration order (razorpay, cashfree). When does order matter (filter chains, pricing rules, fallback gateways), and why should business-critical order be explicit data rather than annotation order spread across classes? - Design a payment routing strategy: Razorpay primary, Cashfree fallback, selected per kitchen by configuration. Should it use
@Primaryplus@Qualifier, or aPaymentRouterthat receivesMap<String, PaymentGateway>and chooses at run time? Justify.
T4. The bean lifecycle
- Walk through P2's order:
- constructor;
- setter and field injection;
Awarecallbacks;BeanPostProcessor.postProcessBeforeInitialization;@PostConstruct;InitializingBean.afterPropertiesSet;- a custom
initMethod; postProcessAfterInitialization, where proxies are created;SmartLifecycle.start;ContextRefreshedEvent;- at shutdown:
SmartLifecycle.stop,@PreDestroy,DisposableBean.destroy.
Which hook do you use for:
- validating configuration;
- opening a connection pool;
- starting a message consumer;
- warming a cache;
- closing resources?
2. Why are proxies created after initialisation (step 8)? What does that mean for code in @PostConstruct that calls the bean's own @Transactional or @Async methods: the proxy doesn't exist yet, and it's self-invocation anyway (the lab)?
3. Startup and shutdown ordering between beans: dependency order (dependencies initialised first, destroyed last), SmartLifecycle phases (consumers stop before the database pool), and graceful shutdown (ch44's T1). Design the phases for TiffinBox: HTTP server, Kafka consumer, scheduler, database pool, cache warmer.
T5. Scopes
- Explain the scopes: singleton, prototype, request, session, application, websocket, and custom scopes (thread, refresh). The lab: a prototype
Cartinjected into a singletonCheckoutAstayed the same cart forever, while anObjectProvidergave new ones (#2, #3). Why does injection time decide this? - Explain scoped proxies (
@RequestScope, which usesproxyMode = TARGET_CLASS): a singleton holds a proxy that resolves to the current request's instance on each call. When is that convenient (request-level caches, the current tenant), and when is it dangerous (async threads with no request context:IllegalStateException: No thread-bound request found)? - Thread safety: singletons are shared by all request threads (or virtual threads: ch38). List the stateful-singleton bugs (mutable fields,
SimpleDateFormat, lazily initialised caches without synchronisation, ch44's P6 cart bug) and the fixes.
T6. Environment, profiles and property sources
- The
Environmenthas active profiles and an ordered list ofPropertySources (system properties, environment variables, files: Boot adds about 15 sources, ch47). P5 found: - a plain context injected the literal${tiffinbox.db.url}for a missing property; - with aPropertySourcesPlaceholderConfigurer(static@Bean), it failed withCould not resolve placeholder 'tiffinbox.db.url'; - with-Dtiffinbox.db.urlset it resolved, and${tiffinbox.pool:20}defaulted to 20.
Explain why the configurer must be a static @Bean, and the risk of defaults that hide missing configuration.
2. Profiles. P5: profile dev selected the fake gateway, and prod (via !dev) the real one. Explain @Profile, expressions (!dev, dev & local), default profiles, and why profiles should select infrastructure variants (fake against real gateway; local or cloud configuration) rather than business behaviour. What goes wrong with if (env.acceptsProfiles("prod")) in business code?
3. @Value against typed configuration (@ConfigurationProperties, ch47; or a record built from the Environment). Why are scattered @Value("${…}") annotations hard to maintain, validate and document?
T7. Application events
- Spring's events:
publishEvent(Object),@EventListenermethods, ordering with@Order, conditional listeners (condition = "#event.amountPaise > 10000"), returning an event to chain, andApplicationEventMulticaster. P4 found events are synchronous, on the publisher's thread (sms on main), in@Orderorder, and a throwing listener propagated to the publisher and stopped later listeners (analyticsnever ran). What does that mean for "fire and forget" assumptions? @TransactionalEventListener(AFTER_COMMITby default): why it exists (don't send the SMS if the order transaction rolls back), what happens to events published outside a transaction (dropped, unlessfallbackExecution = true), and the failure gap (the commit succeeds but the listener fails, so the SMS is lost). How does the outbox pattern close the gap (ch51)?- When are in-process events a good design (decoupling modules inside one service: orders publishes
OrderPlaced, loyalty listens), and when are they not (cross-service communication, work that must survive crashes)? How does Spring Modulith formalise them (an event publication registry)?
T8. AOP and how Spring's proxies work
- AOP concepts:
- aspect (a cross-cutting module);
- join point (a method execution, in Spring AOP);
- pointcut (which join points:
execution(* in.tiffinbox..*Service.*(..)), or annotations); - advice (before, after-returning, after-throwing, after, around); - weaving (proxy-based at run time in Spring; compile-time or load-time with AspectJ).
Which Spring features are AOP: @Transactional, @Cacheable, @Async, @Retryable, @PreAuthorize, @Validated methods, @Timed/@Observed?
2. Two proxy kinds. P6: an interface-based JDK dynamic proxy (jdk.proxy2.$Proxy19) isn't an instance of the implementation class, so injecting Razorpay (the class) would fail with BeanNotOfRequiredTypeException. A CGLIB subclass proxy (Razorpay$$SpringCGLIB$$0) is one. Recap the proxy limitations from the lab:
- self-invocation bypasses advice;
- final methods aren't advised (an NPE on the proxy's empty fields);
- private methods aren't advised;
- final classes can't be proxied (Kotlin needs all-open);
- fields read through the proxy are empty.
3. Choose between proxies and AspectJ weaving. When is self-invocation a real need (a batch method calling a @Transactional(propagation = REQUIRES_NEW) method per item)? Compare the fixes: a separate bean, TransactionTemplate programmatically, self-injection with @Lazy, AspectJ load-time weaving. Which is clearest?
T9. DI and AOP in other ecosystems
- Compare DI approaches:
- Spring (run-time reflection plus AOT);
- Guice (run-time, modules, JIT bindings);
- Dagger and Hilt (compile-time code generation, no reflection: Android);
- Micronaut and Quarkus (build-time DI and AOP for fast startup and native images);
- .NET's
IServiceCollection; - NestJS and Angular (TypeScript decorators and metadata, Volume 2 ch23); - Go (constructor functions; Wire for generation; often no container at all); - Python (manual, ordependency-injector).
What does each say about the trade-off between reflection and generation? 2. AOP elsewhere: - decorators in Python and TypeScript; - middleware wrappers in Go; - Kotlin's delegation; - .NET interceptors and source generators; - AspectJ.
Why do languages without a runtime proxy mechanism use explicit wrapping, and is that worse? 3. If TiffinBox's Go notifier and Node BFF need the "same" cross-cutting behaviour as the Spring services (tracing, retries, metrics), how do you get consistency without a shared framework? Consider shared conventions, OpenTelemetry SDKs, sidecars and meshes, and per-language libraries.
Programming exercises
P1. Ambiguity, qualifiers and collections
Register two PaymentGateway beans and inject one into Checkout. Capture the NoUniqueBeanDefinitionException. Fix it five ways:
- @Primary;
- @Qualifier;
- a custom qualifier annotation;
- @Fallback;
- injecting Map<String, PaymentGateway> into a router.
Show orderedStream() with @Order against getBeansOfType order.
P2. The full lifecycle
Write a bean implementing every lifecycle hook (constructor, setter injection, @PostConstruct, InitializingBean, initMethod, SmartLifecycle, a ContextRefreshedEvent listener, @PreDestroy, DisposableBean) plus a BeanPostProcessor, and print the order. Then:
- call a @Transactional-style intercepted method from @PostConstruct, and show that it's not intercepted;
- move the work to SmartLifecycle.start() in another bean, and show that it is.
P3. Full and lite configuration
Reproduce P3: @Configuration (full) returns the same bean when a @Bean method is called twice, while proxyBeanMethods = false (lite) creates new objects. Then:
- write a lite configuration that accidentally creates two connection pools (simulate with a counter), and fix it with method parameters;
- measure startup with 500 @Bean definitions in full against lite mode.
P4. Application events: synchronous, ordered, failing
Publish OrderPlaced to three ordered listeners where the second throws, and observe:
- the thread;
- the order;
- the exception propagating to the publisher;
- the third listener skipped.
Then fix it three ways:
- make the non-critical listener catch and log;
- make it @Async (with @EnableAsync and an executor), and show the publisher no longer fails;
- describe the @TransactionalEventListener and outbox variants, and what each guarantees.
P5. Property sources, placeholders and profiles
Show:
- a missing @Value placeholder injected literally in a plain context;
- the strict failure with a static PropertySourcesPlaceholderConfigurer;
- a system property resolving it;
- a default value.
Then build a typed PaymentsConfig record from the Environment with validation, and a dev/prod profile pair that switches fake and real gateways. Add a test that fails if any ${…} string reaches a bean.
P6. Proxies: JDK against CGLIB, and the traps
With ProxyFactory, create:
- an interface proxy and a class proxy for Razorpay;
- instanceof checks;
- a counting interceptor.
Reproduce the lab's traps:
- self-invocation not intercepted;
- final method on the proxy (NPE);
- reading a field through the proxy (null).
Fix self-invocation with: - a separate bean; - programmatic interception; - an injected self proxy.
P7. Keeping the domain free of Spring
Take a domain with CheckoutService (plain Java, constructor dependencies on ports) and adapters (JdbcOrderRepository, RazorpayGateway). Wire it three ways:
- a manual composition root (ch44's P6);
- @Configuration with @Bean methods, with no annotations in the domain;
- component scanning of the adapters only.
Write an ArchUnit-style check (or a simple class-scanning test) that fails if any domain class imports org.springframework.
P8. Scopes and scoped proxies
Reproduce the lab's prototype-in-singleton bug and the ObjectProvider fix. Then, with a simulated request context (a ThreadLocal-backed custom scope registered on the context):
- create a "request"-scoped RequestInfo with a scoped proxy;
- show two threads seeing different values;
- show an async task failing to find the scope.
Replace it with an explicit parameter and compare.
P9. The same wiring with Guice, Dagger-style codegen and Go
Wire CheckoutService and its dependencies with:
- Guice (if available; otherwise describe the module);
- a hand-written "generated" factory in the Dagger style;
- Go constructor functions in main.
Compare startup, error detection (a missing binding), and readability. Then implement a logging and timing decorator in Go and in Java (a JDK proxy) for the same interface.
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–46)
C1. Wire the order service with Spring, cleanly
Move ch44's C1 order service onto Spring Framework (core, without Boot):
- a plain-Java domain and application layer;
- @Configuration wiring in an adapter module (lite mode, parameters);
- typed configuration from the Environment with a strict placeholder configurer;
- profiles for fake and real gateways;
- SmartLifecycle phases for the HTTP server and a scheduled job;
- application events between orders and loyalty (with the failure policy from P4);
- proxy-based cross-cutting (timing and logging via ProxyFactory or @Aspect if AspectJ is available);
- tests at three levels: domain without Spring, slices with a small context, full context.
Combines: ch34's aggregate, ch37's functional core, ch38's executors, ch43's modules, ch44's service skeleton and ch45's API, with this chapter.
C2. A plugin-style pricing pipeline with Spring
Build TiffinBox's pricing pipeline (ch34's C2) as Spring beans:
- each rule is a bean implementing PricingRule, named by its configuration key;
- the pipeline order comes from configuration (pricing.rules.HYD=festival,weekend,rain), built from Map<String, PricingRule> with startup validation;
- rule parameters bind from properties;
- a new rule is added by adding a bean, with no pipeline change.
Add tests that the pipeline fails startup on an unknown rule name, and that order follows configuration rather than @Order.
Combines: ch34's composition, ch36's generics (PricingRule with a typed context), ch37's pure functions, and this chapter's collection injection and configuration.
C3. Startup-time budget
Measure TiffinBox's context startup: bean count, time per configuration class, classpath scanning time, proxy creation. Use:
- ApplicationStartup with BufferingApplicationStartup (Spring's startup tracking);
- -Xlog:class+load counts.
Reduce startup by 30% or more with: - lite configuration; - narrower component scanning; - lazy beans for rarely used features; - removing unused proxies; - an AOT or JVM AOT cache.
Report the before and after numbers per step.
Combines: ch39's AOT cache, ch40's class loading and JIT, ch41's measurement method, and this chapter.
What the chapter leaves out
BeanFactoryPostProcessors, BeanDefinitionRegistry and framework extension
Frameworks built on Spring (Boot, Data, Security, Cloud) extend the container by registering bean definitions programmatically (ImportBeanDefinitionRegistrar, BeanDefinitionRegistryPostProcessor, Spring 7's BeanRegistrar), and by post-processing beans. Application code rarely needs these, but reading them explains where "magic" beans (repositories from interfaces, security filter chains) come from. Start with @EnableJpaRepositories's registrar to see how interfaces become beans.
SpEL and its security implications
The Spring Expression Language powers @Value("#{…}"), @PreAuthorize("hasRole('ADMIN')"), @Cacheable(key = "#id") and conditional event listeners. It's powerful, and dangerous when expressions are built from user input: SpEL injection gives remote code execution (several Spring CVEs, such as Spring4Shell's neighbours and Spring Cloud Function's routing expression CVE-2022-22963). Never evaluate untrusted strings as SpEL. Use SimpleEvaluationContext when evaluation of semi-trusted input is unavoidable.
Testing with the Spring TestContext framework
Spring's test support caches contexts between tests (identical configuration means the same context), supports @MockitoBean (Spring 6.2+, replacing Boot's @MockBean), @DynamicPropertySource and slice configurations. Context caching matters for test speed: tests with unique configurations each start a new context. Chapter 54 covers testing strategies.
Resilience annotations in Spring Framework 7
Spring Framework 7 adds core resilience features: @Retryable and @ConcurrencyLimit (with @EnableResilientMethods), based on proxies. They carry the same self-invocation caveats as other proxy-based annotations. Chapter 52 covers resilience patterns and libraries (resilience4j) in depth.
Kotlin and Spring
Kotlin classes are final by default, so proxies need the kotlin-spring (all-open) compiler plugin. Constructor injection is idiomatic, and Spring supports Kotlin's null safety in injection (nullable means optional) and offers the bean definition DSL (beans { bean<CheckoutService>() }). If TiffinBox allows Kotlin modules (ch39's C3), configure these plugins in the convention plugins (ch43).
Senior exercises
S1. Spring usage guidelines for the team
Write the guidelines:
- constructor injection only;
- the domain free of Spring;
- @Bean configuration in lite mode with parameters;
- no getBean or ApplicationContextAware in application code;
- ambiguity resolved with custom qualifiers or routers;
- business order as data;
- singletons stateless;
- ObjectProvider for prototypes, and scoped proxies rarely;
- profiles for infrastructure only;
- typed configuration;
- events (synchronous by default; transactional or outbox for side effects);
- proxy rules (no self-invocation of advised methods, no final advised methods);
- startup budget.
Tie each rule to an output from this chapter and the lab.
S2. Review a Spring-heavy pull request
A PR introduces:
- @Component class CheckoutService with @Autowired fields for 11 dependencies;
- @Transactional private void reserveStock() called from checkout();
- a @Configuration class with proxyBeanMethods = false whose @Bean methods call each other;
- @EventListener for OrderPlaced that sends an SMS synchronously;
- @Profile("prod") on a bean that adds a GST surcharge;
- a static SpringContext.getBean(PricingRules.class) used inside a domain entity.
Write the review.
S3. Decide between Spring, Micronaut/Quarkus and plain Java for a new service
TiffinBox needs a new "kitchen printer bridge" service: it receives order events and sends formatted tickets to on-premise printers through a WebSocket per kitchen, runs on small instances (256 MB), and must start in under a second for scale-to-zero. Decide between Spring Boot (with AOT or native image), Micronaut or Quarkus, and plain Java with the JDK HTTP server and manual DI.
S4. Teach "Spring is just objects and proxies" with five outputs
Prepare a 20-minute session using:
- P1's ambiguity failure;
- P2's lifecycle order;
- P3's full-against-lite @Bean calls;
- P4's synchronous failing listener;
- the lab's self-invocation (@Cacheable body ran 2 times).
For each, explain the underlying mechanism in plain Java terms: "the container calls your constructor", "a subclass intercepts calls", and so on.
S5. Plan the modularisation of a large Spring monolith
TiffinBox's original monolith has 1,400 beans in one Spring context: orders, kitchens, payments, loyalty, notifications and admin, with cross-package @Autowired everywhere, circular references enabled by a property, ApplicationContextAware helpers and synchronous events used as cross-module calls. Plan a 6-month modularisation into a modular monolith (Spring Modulith) as a step towards possible service extraction.