Sub topic 1
Inversion of Control: Who Creates Your Objects?
Prerequisites
This chapter assumes you know Java classes, interfaces, constructors, annotations, and object composition. You should also know how to add Spring dependencies with Maven or Gradle.
Inversion of control: who creates your objects?
Inversion of control (IoC) means that a framework controls object creation and wiring instead of application code doing it directly.
Without IoC, a class might create its dependency with new. That class then knows the dependency's concrete implementation and controls its lifetime. With IoC, the class declares what it needs, and Spring supplies it.
Dependency injection and why it reduces coupling
Dependency injection (DI) is the technique IoC uses to provide an object's dependencies. A dependency is an object another object needs to do its work.
Constructor injection makes the dependency explicit:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class Main {
interface MessageSender {
void send(String to, String body);
}
static class NotificationService {
private final MessageSender sender;
NotificationService(MessageSender sender) {
this.sender = sender;
}
void welcome(String user) {
sender.send(user, "Welcome!");
}
}
@Configuration
static class AppConfig {
@Bean
MessageSender sender() {
return (to, body) -> System.out.println(to + ": " + body);
}
@Bean
NotificationService service(MessageSender sender) {
return new NotificationService(sender);
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
context.getBean(NotificationService.class).welcome("ana");
}
}
}NotificationService depends on the MessageSender interface, not on email or SMS details. Tests can provide a fake sender, and production configuration can provide a real one.
What a Spring bean is
A Spring bean is an object that Spring creates, configures, and manages. Spring can register beans through annotations such as @Component and @Service, or through methods marked @Bean in a @Configuration class.
The container can also manage a bean's scope, initialization, destruction, and dependencies. A bean is therefore more than an ordinary object created with new: its lifecycle is under Spring's control.
The ApplicationContext as the container
ApplicationContext is Spring's central container. It reads configuration, creates beans, resolves dependencies, and makes beans available to application code. In the example, closing the context also allows managed beans to release resources.
Exercise
Why does constructor injection reduce coupling?
Show answer
The class depends on an abstraction supplied from outside, so it does not create or select a concrete implementation.