Part 1: Spring IoC and Dependency Injection
Key concepts
- Dependency
- An object or capability another object needs to do its work.
- IoC
- Inversion of Control: infrastructure takes responsibility for tasks such as creating and assembling application objects.
- DI
- Dependency Injection: supplying a needed object from outside the object that uses it.
- Bean
- An object managed by the Spring container; it is not simply any object created with new.
Ask two questions separately: who creates the service, and who supplies its repository? With constructor injection, the service states what it needs in its constructor. Spring chooses a compatible registered bean and supplies it. The service can then focus on its business operation.
Example: A test can supply a small in-memory repository while the application supplies a database repository. Both satisfy the same interface. The service need not choose either implementation.
Example: Constructor injection
This example supplies a dependency through a constructor. It runs as plain Java; the later Spring examples show how the container supplies that dependency.
Save as InjectionDemo.java. With Java 17 or later, run javac InjectionDemo.java, then java InjectionDemo.
public class InjectionDemo {
interface Names { String first(); }
static class Greeting {
private final Names names;
Greeting(Names names) { this.names = names; } // Supply the dependency.
String message() { return "Hello, " + names.first(); }
}
public static void main(String[] args) {
Names sample = () -> "Asha"; // A tiny substitute for a repository.
Greeting greeting = new Greeting(sample);
System.out.println(greeting.message()); // The service uses its collaborator.
}
}
Expected output
Hello, Asha
Explain container-managed objects and compare constructor, setter and field injection.
Course Outcome (CO) states what a learner should be able to do after the course; CO1 to CO5 label the five syllabus outcomes.
Learning outcome: Explain container-managed objects and compare constructor, setter and field injection.
Start here: Start with one relationship: StudentService needs StudentRepository. Learn who creates the objects, how the repository reaches the service, and why constructor injection makes that requirement clear.
Introduction
Objects in an application work together. A controller calls a service; the service uses a repository to access data. The repository is a dependency of the service because the service needs it to do its work.
If every class creates its own collaborators, the choice of implementation becomes scattered through the code. Supplying those collaborators from outside makes them easier to replace and test.
Spring Framework is a modular Java application framework that provides infrastructure for assembling application objects and supporting concerns such as transactions, data access and web request handling. Its Core container implements Inversion of Control and dependency injection. Application classes can concentrate on their own operations while the container assembles their collaborators.
This lesson introduces those terms before comparing injection techniques. It builds on Java classes, constructors, interfaces and composition. Spring Boot is introduced in Lesson 3; it uses Spring Framework and simplifies application configuration and startup.
Learning objectives
After completing this lesson, you should be able to:
Dependency Injection (DI) supplies an object's collaborators from outside instead of having the object construct them itself.
- Define a dependency, coupling, IoC, DI and a Spring bean.
- Explain what the Spring IoC container and ApplicationContext manage.
- Distinguish registering a bean from injecting a dependency.
- Compare constructor, setter and field injection.
- Explain how type matching, qualifiers and primary beans affect dependency selection.
Key terms and definitions
| Term | Definition | Example or significance |
|---|---|---|
| Framework | Reusable software infrastructure that provides conventions and execution points for application code. | Spring invokes configured components through its infrastructure. |
| Dependency | An object or capability that another object needs to perform its work. | StudentService needs a StudentRepository. |
| Coupling | The degree to which a component depends on the details of another component. | Constructing a specific database implementation inside a service ties them together. |
| Inversion of Control (IoC) | An arrangement in which infrastructure takes responsibility for control that application code would otherwise manage directly. | Spring creates and wires configured application objects. |
| Dependency injection (DI) | Supplying an object's collaborators from outside rather than having that object create or locate them itself. | Passing a repository to a service constructor. |
| Spring bean | An object instantiated, assembled and managed by the Spring IoC container. | A registered StudentService instance. |
| IoC container | The infrastructure that reads configuration and creates, wires and manages beans. | An ApplicationContext implementation. |
| Bean definition | Configuration metadata describing how a bean is created and configured. | Its type, scope and constructor dependencies. |
| BeanFactory | Spring's foundational container interface for bean management and lookup. | Provides the basic container contract. |
| ApplicationContext | A BeanFactory subinterface with additional application facilities. | Events, message resources and integration with framework infrastructure. |
| Annotation | Metadata attached to Java code and interpreted by a compiler, tool or runtime framework. | Spring interprets @Component and @Autowired. |
| Component scanning | Searching configured packages for eligible annotated components and registering their definitions. | Finding a service in the application's package tree. |
| Autowiring | Resolving and supplying a managed dependency according to injection metadata and eligible candidates. | Selecting a bean compatible with a constructor parameter. |
| Qualifier | Metadata used to narrow the set of eligible injection candidates. | Choosing one of two repository implementations. |
DI is one form of IoC. It can also be performed manually in ordinary Java: a caller can construct a repository and pass it to a service. Spring adds container-managed assembly; DI does not require every class to know about the container.
- Create: a caller creates an object that implements the repository contract.
- Supply: the caller passes that object to the service constructor.
- Use: the service calls the supplied repository instead of choosing and creating a storage implementation itself.
This is manual DI. With Spring, the container performs the creation and supply steps from your configuration. The service still declares the dependency it needs.
From direct construction to injected collaboration
Java Database Connectivity (JDBC) is Java's standard interface for connecting to relational databases, issuing statements and reading results.
Consider a service that creates a concrete JDBC repository internally. The service controls both its business operation and the choice of storage implementation. Changing storage or testing with an in-memory substitute then requires changes to its construction logic.
With injection, the service declares the collaborator it needs. A caller or container chooses and supplies an implementation. Depending on an interface can reduce reliance on implementation details, provided that the interface expresses a useful contract. DI does not eliminate all coupling: the service still depends on that contract.
In the chapter project, the service declares a StudentRepository dependency and Spring Data provides an eligible implementation. Spring assembles the service with that repository. Hibernate-managed entity instances remain distinct from Spring-managed service beans.
ApplicationContext
├─ StudentRepository implementation
└─ StudentService(repository)
Spring architecture and related projects
For this lesson, focus on Core/Beans, which describes and assembles beans, and Context, which adds application-level services. Spring Expression Language (SpEL) evaluates expressions.
Object-Relational Mapping (ORM) maps objects in a program to rows and relationships in a database. Model-View-Controller (MVC) separates application data and rules, user-facing presentation, and request or input handling.
The other modules provide context for later study: data-access support integrates JDBC, transactions and ORM; Spring MVC handles servlet-based web requests; WebFlux provides a reactive web stack; and Spring Test supports unit and integration tests.
Aspect-oriented programming (AOP) separates cross-cutting behaviour from the main operation. An aspect groups such behaviour; advice is the action applied, and a pointcut selects where it applies. Spring AOP commonly uses proxies around method calls. Transaction interception is a practical example: begin/join a transaction, invoke the service and then commit or roll back. Proxy interception has limitations, including ordinary self-invocation.
Simple Object Access Protocol (SOAP) is the historical expansion of SOAP, a protocol for structured messages using Extensible Markup Language envelopes. Representational State Transfer (REST) is an architectural style that organises a web service around resources, such as students or products, accessed through a consistent interface.
Spring Data, Security, Integration, Batch and Cloud are related Spring projects, not all modules embedded in Spring Core. They address persistence repositories, access control, messaging, batch work and distributed-system support respectively. Spring Web Services focuses on SOAP; ordinary REST applications use MVC or WebFlux. Using one Spring project does not automatically enable all of them.
Configuration styles
Extensible Markup Language (XML) represents structured data using named elements and attributes.
Spring accepts XML bean definitions, component annotations and Java configuration. XML uses bean definitions, constructor-arg for constructor values and property for setter properties. Java configuration uses @Configuration and @Bean; scanning discovers components annotated with stereotypes. These styles can be combined when required.
For example, an XML definition can declare a service with a constructor reference to a repository. The equivalent Java configuration supplies that repository as a factory-method parameter. Injection is the dependency relationship; XML or Java annotations are ways of describing it. A manually configured container can read XML with ClassPathXmlApplicationContext; older XmlBeanFactory examples should not be copied into the chapter's modern Spring baseline.
Container responsibilities
Think of a bean definition as a recipe and a bean instance as the object made from that recipe. The container reads the configuration, records the recipes, resolves dependencies and creates the objects.
Bean post-processors can then inspect or wrap an object. A wrapper called a proxy can add behaviour such as transaction handling around a method call. Application services normally receive their dependencies through injection; they do not repeatedly ask the container to find them.
A small context can be started without Boot. The following fragment loads the CourseConfiguration class from the bean lesson and retrieves its Clock bean:
try (AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(CourseConfiguration.class)) {
Clock clock = context.getBean(Clock.class);
System.out.println(clock.getZone());
}
Coordinated Universal Time (UTC) is the international reference time standard used to express timestamps consistently.
Import java.time.Clock and org.springframework.context.annotation.AnnotationConfigApplicationContext. The zone printed is Z for the configured UTC clock. Closing the context triggers managed cleanup. Normal application services should receive dependencies through injection rather than repeatedly looking them up from the context.
Compare dependency injection choices
Consider a service that needs a repository. Select a style, then compare its construction and testing implications with the code examples below.
Constructor injection
The caller must supply the repository when constructing the service. The dependency can be final, and plain Java tests can supply a substitute. This is usually the clearest choice for a required collaborator.
Setter injection
The collaborator is supplied after construction. This permits reconfiguration, but the object needs a well-defined usable state. An Autowired setter is required by default; optionality must be configured deliberately.
Field injection
The container populates the field. The constructor does not reveal the dependency, and a plain new call leaves it unpopulated unless another mechanism supplies it. Constructor injection generally makes required dependencies and tests clearer.
Constructor injection for required collaborators
@Service
public class StudentService {
private final StudentRepository students;
public StudentService(StudentRepository students) {
this.students = students;
}
}
This is a fragment of the full service developed later. Its repository requirement is visible and the field can be final. A single constructor needs no @Autowired in modern Spring. A plain unit test can construct it with a suitable test repository. Automatic transaction interception, however, requires a managed/proxied service.
Setter and field alternatives
@Autowired
public void setStudents(StudentRepository students) {
this.students = students;
}
Setter injection permits wiring after construction. An @Autowired setter is required by default; optional injection must be chosen explicitly. For required collaborators, a constructor usually makes the class contract clearer.
@Autowired
private StudentRepository students;
Field injection hides the dependency from callers and makes plain Java construction/testing less convenient. These are alternative designs: do not add all three forms to the same service. An annotation on an object created with new does not automatically cause Spring to inject it.
Resolving a bean
Spring primarily matches by type. If two implementations are eligible, use @Qualifier at the injection point or @Primary on a default bean. A qualifier narrows candidates; it does not create a missing implementation.
If Spring reports that a dependency is missing, check the configuration before changing the injection style:
- Is the implementation registered through a component annotation, a factory or another supported mechanism?
- Does component scanning include its package?
- Is the required profile active, and has the configuration been imported?
In the Boot example, put the application class in a parent package of the application components. A constructor cycle, such as A needing B while B needs A, normally prevents creation; separate the responsibilities instead of adding more injection annotations.
Registration versus injection
Application Programming Interface (API) defines the operations one software component can use to communicate with another. Java Persistence API (JPA) lets Java code save and load objects as database rows. The standard is now called Jakarta Persistence.
@Component and @Bean register bean definitions. @Autowired marks an injection point. These solve different steps of assembly. The service's repository interface is implemented at runtime by Spring Data JPA; an arbitrary Java interface without an implementation or factory is not injectable by itself.
Summary
Spring assembles managed objects from configuration metadata. IoC describes the transfer of control, and DI supplies collaborators from outside an object. Bean registration, dependency selection and injection are separate steps. Constructor injection makes required dependencies explicit.
Practice
- Draw Controller → Service → Repository dependencies.
- Convert a field-injected service to constructor injection.
- Explain how Qualifier resolves two eligible implementations.
Quick check
Check your understanding
Are IoC and DI identical? DI is a way to provide collaborators; IoC is the broader transfer of control to a container or framework.
Further reading
Review questions
1. Does @Autowired create an implementation for every Java interface?
Answer: No. It requests injection. A compatible implementation must already be registered or supplied by a supported factory, such as Spring Data.
2. Why is constructor injection useful for a required dependency?
Answer: An object cannot be constructed normally without that dependency, and a test can supply it explicitly. The dependency is visible in the class contract.