Spring dependency injection
What you will learn
Dependency injection means receiving collaborators instead of creating them inside a service. Spring’s inversion-of-control container builds and manages the object graph. Start with ordinary Java constructor injection: the framework is optional for the domain logic.
- Wire a domain service through an interface.
- Register and retrieve beans in a small Spring context.
- Diagnose missing or ambiguous dependencies.
Plain Java examples use javac --release 21 Main.java then java Main in a fresh folder. Framework examples require the separate pinned Maven lab; their outputs are predictions from source review, not execution evidence. Do not copy all files into one Main.java.
Inject a price source without Spring
public class Main { interface Prices { int cents(String sku); } record Quote(Prices prices) { Quote { java.util.Objects.requireNonNull(prices); } int total(String sku, int quantity) { if (quantity < 1) throw new IllegalArgumentException("quantity"); return Math.multiplyExact(prices.cents(sku), quantity); } } public static void main(String[] args) { Quote quote = new Quote(sku -> 125); System.out.println(quote.total("PEN", 3)); }}Expected output:
375The lambda is an in-memory implementation of Prices; no container is needed.
The object graph
A service that constructs a concrete repository internally decides both its behavior and its dependency. Instead accept a repository interface in the constructor, validate it, and keep it in a final field. The composition root chooses the implementation. A fake can be injected in a test. BeanFactory supplies the basic container contract; ApplicationContext adds capabilities such as events, resource access and environment integration. Spring Framework is a library, not part of Java SE. Spring Boot builds on it and provides conventions and auto-configuration; neither is needed for plain Java DI.
Register beans and resolve dependencies
A bean is an object registered with a Spring container. A configuration class marked @Configuration can expose factory methods marked @Bean. A method parameter is resolved by the container; this makes dependencies explicit even when proxyBeanMethods=false. Alternatively, scan a deliberately narrow application package using @ComponentScan(basePackageClasses=SomeComponent.class); @Component and @Service are stereotypes. A single constructor normally needs no @Autowired. Avoid the unnamed package for scanning. If multiple beans implement an interface, select a @Primary default or use @Qualifier("name") at the injection site. Missing required dependencies or unresolvable ambiguity normally prevent eager singleton creation at refresh. Constructor cycles require redesign, not field injection as a blanket fix.
Context setup and ownership
The local lab pins Spring Framework 7.0.9 via spring-context and spring-tx. It uses JDK 21, Maven and no Boot starter or server. Register configuration, set profiles and property sources before refresh if needed, retrieve the entry service, then close the context. Do not scatter getBean calls through domain services: that hides dependencies. Calling a factory method directly in lite configuration or with proxyBeanMethods=false is an ordinary Java call, not container lookup.
Swap the dependency in a test
public class Main { interface Stock { int remaining(String sku); } record Availability(Stock stock) { boolean canShip(String sku, int quantity) { return quantity > 0 && stock.remaining(sku) >= quantity; } } public static void main(String[] args) { var enough = new Availability(sku -> 4); var empty = new Availability(sku -> 0); System.out.println(enough.canShip("PEN", 4)); System.out.println(empty.canShip("PEN", 4)); }}Expected output:
truefalseThe same service works with two independently supplied implementations.
Wire a real Spring context
Source-reviewed, NOT RUN. File lab-fixtures/spring-v37/src/main/java/lab/spring/InjectionDemo.java; use the companion Maven lab instructions.
package lab.spring;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;public class InjectionDemo { interface Prices { int cents(String sku); } record Quote(Prices prices) { int total(String sku, int quantity) { if (quantity < 1) throw new IllegalArgumentException("quantity"); return Math.multiplyExact(prices.cents(sku), quantity); } } @Configuration(proxyBeanMethods = false) static class Config { @Bean Prices prices() { return sku -> 125; } @Bean Quote quote(Prices prices) { return new Quote(prices); } } public static void main(String[] args) { try (var context = new AnnotationConfigApplicationContext(Config.class)) { System.out.println("quote=" + context.getBean(Quote.class).total("PEN", 3)); } }}Predicted stdout:
quote=375The factory method receives the registered Prices bean. The service remains ordinary Java.
Common mistakes
Do not instantiate a dependency inside a service if the caller needs to substitute it. Do not treat @Autowired as a Java instruction: newing an object directly does not make Spring inject anything. Avoid broad component scanning and ambiguous bean types; choose a specific implementation deliberately.
Practice
Write a shipping quote service that receives a rate interface; reject negative weight, return cents using Math.multiplyExact, and exercise two rates. Then describe how two Spring beans of that interface could be disambiguated.
Expected output:
240360Compare with the manual review criteria.
Official reading: DI · Configuration · Scanning · Bean. Framework execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Spring dependency injection — knowledge check
Spring fundamentals and boundary reasoning.
What is constructor injection?
Which annotation marks a factory method in Java configuration?
What does a single required constructor normally need for Spring injection?
How can a required injection site select one of two same-type beans?
What is the benefit of a narrow component scan?