// 传统方式 - 对象自己管理依赖 public class UserService {
private UserRepository userRepository = new UserRepository();
}
@Service public class OrderService {
private final PaymentProcessor paymentProcessor;
private final InventoryService inventoryService;
@Autowired
public OrderService(PaymentProcessor paymentProcessor,
InventoryService inventoryService) {
this.paymentProcessor = paymentProcessor;
this.inventoryService = inventoryService;
}
}
@Service public class UserService {
private final UserRepository userRepository;
private NotificationService notificationService;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Autowired
public void setNotificationService(NotificationService notificationService) {
this.notificationService = notificationService;
}
}
@Component public class ServiceA {
private final ServiceB serviceB;
public ServiceA(ServiceB serviceB) {
this.serviceB = serviceB; // 等待ServiceB创建
}
}
@Component
public class ServiceB {
private final ServiceA serviceA;
public ServiceB(ServiceA serviceA) {
this.serviceA = serviceA; // 等待ServiceA创建
}
}
你可能想看:
Java优学网@Autowired入门解析:掌握Spring依赖注入,轻松实现高效开发
Java优学网Spring IoC讲解:轻松掌握控制反转与依赖注入,告别代码耦合烦恼
Java优学网Spring自动装配教程:轻松掌握依赖注入,提升开发效率40%
Java优学网Spring注解短文:轻松掌握Spring核心注解,告别繁琐配置,高效开发Java应用
Java优学网Spring Bean创建讲解:轻松掌握Bean生命周期与依赖注入技巧
Java优学网Spring Bean配置教程:从XML到注解,轻松掌握依赖注入与Bean生命周期管理