#Why Spring exists
AddedEvery real application has a graph of objects: a controller needs a service, the service needs a repository and a payment client, the repository needs a database connection pool, which needs configuration. Somebody has to create all of them, in the right order, and hand each one the objects it needs.
In plain Java you do that by hand with new, usually in main. That's fine for five classes and painful for five hundred, and it hard-codes choices (which payment client? which database?) into the wiring code. Spring is a container that does the wiring for you. You mark your classes, declare what each one needs in its constructor, and Spring creates every object once, works out the order, and passes them in. That's inversion of control: your classes don't create their dependencies or look them up; they're given them. Handing them in is dependency injection (DI).
For a Node.js developer the closest picture is this: in Node, require("./db") gives every file the same module instance, so modules act as singletons and you wire things by importing them. That works, but it couples files to concrete implementations, and swapping one in a test needs tricks like jest.mock. NestJS is the Node framework that works like Spring (and was modelled on Angular, which got the idea from Spring): @Injectable() classes and constructor injection. If you've used NestJS or Angular services, you already know the shape.
The same classes wired two ways: by hand in plain Java on the left, and by Spring on the right (a file in the starter project, plus the four-line application.properties from the top of this chapter).
interface PaymentGateway {
String charge(long cents);
}
class CardGateway implements PaymentGateway {
public String charge(long cents) {
return "charged " + cents + " cents to the card";
}
}
interface Notifier {
void send(String message);
}
class EmailNotifier implements Notifier {
public void send(String message) {
IO.println("email: " + message);
}
}
class OrderService {
private final PaymentGateway payments;
private final Notifier notifier;
OrderService(PaymentGateway payments, Notifier notifier) {
this.payments = payments;
this.notifier = notifier;
}
void place(String item, long cents) {
notifier.send(item + ": " + payments.charge(cents));
}
}
void main() {
var orders = new OrderService(new CardGateway(), new EmailNotifier());
orders.place("Keyboard", 4999);
}$ java Main.java
email: Keyboard: charged 4999 cents to the cardpackage com.example.shop;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
interface PaymentGateway {
String charge(long cents);
}
@Component
class CardGateway implements PaymentGateway {
public String charge(long cents) {
return "charged " + cents + " cents to the card";
}
}
interface Notifier {
void send(String message);
}
@Component
class EmailNotifier implements Notifier {
public void send(String message) {
System.out.println("email: " + message);
}
}
@Service
class OrderService {
private final PaymentGateway payments;
private final Notifier notifier;
OrderService(PaymentGateway payments, Notifier notifier) {
this.payments = payments;
this.notifier = notifier;
}
void place(String item, long cents) {
notifier.send(item + ": " + payments.charge(cents));
}
}
@Component
class PlaceAnOrder implements CommandLineRunner {
private final OrderService orders;
PlaceAnOrder(OrderService orders) {
this.orders = orders;
}
@Override
public void run(String... args) {
orders.place("Keyboard", 4999);
}
}spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn$ ./mvnw -q spring-boot:run
email: Keyboard: charged 4999 cents to the card- By hand (left):
OrderServicedoesn't create its collaborators; it receives aPaymentGatewayand aNotifierin its constructor and keeps them infinalfields. That's already dependency injection. It depends on interfaces, so a test can pass a fake gateway without changingOrderService. mainis the wiring: it decides which implementations exist and callsnewfor each, inner ones first. It printsemail: Keyboard: charged 4999 cents to the card. The weak spot ismainitself: with hundreds of classes it's long, order-sensitive, and changes every time a constructor does.- With Spring (right): the classes are the same plus annotations.
@Component(and@Service, the same thing with a more specific name) says "Spring, create one of these and manage it". A managed object is a bean. - There's no
newanywhere. At startup Spring finds the four annotated classes, sees thatOrderService's constructor needs aPaymentGatewayand aNotifier, finds the one bean of each type (CardGateway,EmailNotifier), and creates those first. PlaceAnOrderimplementsCommandLineRunner, so Spring Boot calls itsrunmethod once everything is created: the Spring version of "the code at the bottom ofmain". The starter'sShopApplication(unchanged) is what starts Spring.- Same output,
email: Keyboard: charged 4999 cents to the card. What changed is who decides the wiring: swappingEmailNotifierfor anSmsNotifieris now a change to which class is a bean, not to any constructor call.