在Spring框架中,依赖注入(DI)是一种核心概念,它允许我们以一种松耦合的方式管理组件之间的依赖关系。本文将详细介绍Spring中三种依赖注入的方式,并结合实例代码进行说明。
1. 构造器注入(Constructor-based DI)
构造器注入是Spring推荐的依赖注入方式,适用于必需的依赖。在构造器中,我们应该将参数赋值给final类型的成员变量。
@Configuration
public class ConstBasedDI {
@Bean
public OrderService orderService() {
return new OrderService();
}
@Bean
public OrderServiceClient orderServiceClient() {
return new OrderServiceClient(orderService());
}
public static void main(String... strings) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConstBasedDI.class);
OrderServiceClient bean = context.getBean(OrderServiceClient.class);
bean.showPendingOrderDetails();
}
private static class OrderServiceClient {
private final OrderService orderService;
OrderServiceClient(OrderService orderService) {
this.orderService = orderService;
}
public void showPendingOrderDetails() {
System.out.println(orderService.getOrderDetails("100"));
}
}
}
输出结果:
Order details for order id=100
2. Setter注入(Setter-based DI)
Setter注入适用于可选的依赖。通过Setter方法,我们可以在Spring容器中注入依赖项。
@Configuration
public class SetterBasedDI {
@Bean
public OrderService orderService() {
return new OrderService();
}
@Bean
public OrderServiceClient orderServiceClient() {
return new OrderServiceClient();
}
public static void main(String... strings) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SetterBasedDI.class);
OrderServiceClient bean = context.getBean(OrderServiceClient.class);
bean.showPendingOrderDetails();
}
private static class OrderServiceClient {
private OrderService orderService;
@Autowired
public void setOrderService(OrderService orderService) {
this.orderService = orderService;
}
public void showPendingOrderDetails() {
System.out.println(orderService.getOrderDetails("200"));
}
}
}
输出结果:
Order details for order id=200
3. 字段注入(Field-based DI)
Spring不推荐使用字段注入,因为它可能会隐藏必需的字段,这些字段本应在构造器中被赋值。尽管如此,为了简化概念,我们在这个系列的教程中主要使用了字段注入。
@Configuration
public class FieldBasedDI {
@Bean
public OrderService orderService() {
return new OrderService();
}
@Bean
public OrderServiceClient orderServiceClient() {
return new OrderServiceClient();
}
public static void main(String... strings) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(FieldBasedDI.class);
OrderServiceClient bean = context.getBean(OrderServiceClient.class);
bean.showPendingOrderDetails();
}
private static class OrderServiceClient {
private OrderService orderService;
public void showPendingOrderDetails() {
System.out.println(orderService.getOrderDetails("300"));
}
}
}
输出结果:
Order details for order id=300
版本兼容性
本示例适用于Spring Context的多个版本,包括3.2.9.RELEASE至6.1.2版本。确保使用的Java版本为17或更高。
技术栈
- Spring Context 6.1.2
- JDK 17
- Maven 3.8.1
通过本篇博客,我们深入探讨了Spring依赖注入的三种方式,并提供了实际的代码示例。希望这能帮助您更好地理解和应用Spring框架中的依赖注入。