Sub topic 1
Inversion of control: who creates your objects?
Prerequisites
This chapter assumes you can read and write Java at the level of classes, interfaces, constructors and annotations. You should know what coupling means in object-oriented design, and why composition (one object holding another) is common. You should also be able to add a dependency in Maven or Gradle. You don't need to know Spring yet. The chapter uses it only in the last examples.
The question behind the term
Every object in a program has to come from somewhere. Someone calls a constructor, decides which implementation to use, and decides how long the object lives. Inversion of control (IoC) is a design principle that moves those decisions out of your business code and into a separate piece of code, often a framework.
The name describes who holds control. In a traditional program, your code controls the flow. It creates what it needs and calls the libraries it wants. With IoC, a framework controls the flow, and it calls your code at the right moments. People sometimes call this the Hollywood principle: "don't call us, we'll call you."
Spring's core is an IoC container. This chapter builds the idea in plain Java first, so the Spring version is easy to recognize.
Control without inversion
Here is a service that sends a welcome message. It decides for itself which sender to use.
public class EmailSender {
public void send(String to, String body) {
System.out.println("email to " + to + ": " + body);
}
}
public class NotificationService {
private final EmailSender sender = new EmailSender();
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}This works, but NotificationService controls three things that are not its job:
- Which implementation to use. The field type is the concrete
EmailSender, so switching to SMS means editing this class. - How the dependency is built. If
EmailSenderlater needs a host name and a port,NotificationServicemust now supply them. - How long the dependency lives. Each service creates its own sender, so you can't share one or replace one.
The result is tight coupling. Testing is also hard, because you can't run welcome without a real EmailSender.
Inverting the control
The first step is to depend on an abstraction and receive it from outside.
public interface MessageSender {
void send(String to, String body);
}
public class EmailSender implements MessageSender {
@Override
public void send(String to, String body) {
System.out.println("email to " + to + ": " + body);
}
}
public class NotificationService {
private final MessageSender sender;
public NotificationService(MessageSender sender) {
this.sender = sender;
}
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}NotificationService no longer creates anything. It states what it needs, a MessageSender, and trusts that someone will provide one. The decision about which sender to use has moved elsewhere. In a small program that "elsewhere" can be the main method:
public class Main {
public static void main(String[] args) {
MessageSender sender = new EmailSender();
NotificationService service = new NotificationService(sender);
service.welcome("ana");
}
}This is IoC done by hand. The place where objects are created and connected is called the composition root. In a ten-class program, writing it yourself is fine. In a 500-class application, the composition root becomes long and fragile. Every constructor change ripples into it, and you must get the creation order right yourself. A container automates that work.
Other forms of IoC you already use
IoC is broader than Spring. You have probably met it in these forms:
| Form | Who holds control | Your code's role |
|---|---|---|
| Callback or listener | The event source decides when to fire | Supply the handler |
| Template method | The base class defines the algorithm | Override the steps |
| Servlet container | The server accepts requests and picks the servlet | Implement `doGet` or `doPost` |
| Test runner | JUnit finds, orders and runs the tests | Write annotated test methods |
| Service locator | Your code asks a registry for what it needs | Call the lookup |
| Dependency injection | A container builds and passes in dependencies | Declare what you need |
Dependency injection (DI) is one specific way to achieve IoC, the one that applies to object creation and wiring. The next chapter covers it in detail. For now, keep the two terms apart. IoC is the principle, and DI is a technique that implements it.
A service locator also inverts creation, but your code still calls the locator by name. That keeps a hard-coded reference to the locator inside every class, which is why most Spring code prefers injection.
What the Spring container does
Spring's IoC container takes over the composition root. You give it metadata that describes your objects: annotations on classes, or @Bean methods in a configuration class. At startup the container reads that metadata, creates the objects, connects them, and manages them until shutdown. Objects that the container creates and manages are called beans. The following chapters define beans and the container precisely.
Here is the manual wiring from above, handed to Spring:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MessageSender emailSender() {
return new EmailSender();
}
@Bean
public NotificationService notificationService(MessageSender sender) {
return new NotificationService(sender);
}
}
class SpringMain {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
ctx.getBean(NotificationService.class).welcome("ana");
}
}
}To run this, add spring-context to your build. Notice what changed. NotificationService is identical to the hand-wired version. The @Bean method for the service asks for a MessageSender parameter, and Spring supplies the matching bean. You never call new NotificationService(...) with a sender you picked at the call site. The container decides the creation order and passes the arguments.
The diagram shows the sequence at startup.
Only one thing in your application, the entry point, still touches the container directly. In a typical Spring Boot application even that is hidden, because Boot builds the context for you and your classes never call getBean.
What you gain
- Replaceable parts. Swapping
EmailSenderfor an SMS sender touches one configuration line, not every consumer. - Testability. A test can pass a fake sender straight into the constructor, with no container and no network.
- Central lifecycle management. The container can share one instance, create a new one per request, and run setup and cleanup code. Later chapters cover scopes and lifecycle callbacks.
- Declared dependencies. A constructor signature tells you what a class needs. No hidden
newcalls are buried in method bodies. - Cross-cutting features. Because the container creates your objects, it can wrap them. Transactions, caching and security in Spring work this way.
What you give up, and common errors
IoC has costs, and most beginner mistakes come from forgetting that the container only manages what it creates.
- Calling
newon a managed class. If you writenew NotificationService(...)yourself inside another method, the result is an ordinary object. Spring does not inject into it, wrap it, or call its lifecycle callbacks. Features such as@Transactionalsilently don't apply to it. If a class should be managed, get it from the container. - Mixing up IoC and DI. Saying "Spring is a DI framework" is common and mostly harmless. But when reading documentation, remember that "IoC container" names the whole facility and "injection" names how dependencies are delivered.
- Hidden control flow. Your code no longer shows who calls it or when. A stack trace during startup can run through framework classes you never wrote. Learn to read it from the bottom up and look for your own class names.
- Failure moves to startup. Wiring mistakes, such as a missing dependency, surface when the container starts, not when the line runs. That is usually a benefit, because the application refuses to boot instead of failing in production. It also means a wrong configuration shows up as a long startup error. Later chapters cover diagnosing these.
- Overusing the container. Not every object needs to be a bean. Value objects, DTOs, and short-lived objects built from request data are normally created with
new. Use the container for long-lived collaborators such as services, repositories and clients. - Reaching into the container. Calling
ctx.getBean(...)from business classes brings back the service locator problem. Reserve it for the entry point and for tests that need it.
Summary of the working model
Your classes declare what they need and stop building their own collaborators. A separate piece of code, either your main method or a Spring container, builds the objects and connects them. In Spring, the container reads metadata, creates the beans in dependency order, passes them in, and manages them until shutdown. The next chapter looks at dependency injection, the mechanism that carries the dependencies in.
Exercise
In the first version of NotificationService, the field is initialized with new EmailSender(). Name two concrete problems this causes, then describe the one change that inverts control.
Show answer
Problems (any two): the class is tied to the concrete EmailSender, so changing the sender means editing the service. The service must know how to build the sender, including any settings it needs later. Tests cannot replace the sender with a fake, so they would send real email. The change that inverts control: depend on the MessageSender interface and receive the instance through the constructor, so that the code creating the service (main or the Spring container) chooses and builds the sender.
Exercise
A teammate writes NotificationService service = new NotificationService(new EmailSender()); inside a controller method and says the class is a Spring bean because it carries @Service. Is that correct? What would you change?
Show answer
No. Only objects created by the container are beans. An instance made with new receives no injection, no proxies (such as transactions) and no lifecycle callbacks. Change the controller to declare a NotificationService constructor parameter so Spring injects the managed bean.