Vấn đề Spring giải quyết
Không có Spring, bạn phải tự tạo và quản lý dependencies:
// Tight coupling — class tự tạo dependency
public class OrderService {
private PaymentGateway payment = new StripePayment(); // hardcoded!
private EmailService email = new SmtpEmailService(); // hardcoded!
public void placeOrder(Order order) {
payment.charge(order.getTotal());
email.send(order.getCustomerEmail(), "Order confirmed");
}
}
Vấn đề: muốn đổi Stripe sang PayPal? Phải sửa code. Muốn test? Không mock được.
Dependency Injection
Spring đảo ngược quyền kiểm soát (Inversion of Control): thay vì class tự tạo dependency, Spring inject vào:
@Service
public class OrderService {
private final PaymentGateway payment;
private final EmailService email;
// Spring tự inject đúng implementation
public OrderService(PaymentGateway payment, EmailService email) {
this.payment = payment;
this.email = email;
}
}
Spring Boot — Convention over Configuration
Spring Boot = Spring + auto-configuration + embedded server:
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
// Embedded Tomcat starts automatically
}
}
Key insight: Spring Boot không phải framework mới — nó là opinionated setup của Spring. Hiểu Spring Core trước, dùng Boot sau.