spring - 为什么注入 bean 仍然需要更改代码?
问题描述
我是 Spring 新手,我知道 DI 的基本原理。我无法理解的是,如果我们希望更改 bean 类型,我们仍然需要在 Parent 类中进行代码更改。
例如,在下面的代码中,我们需要在服务类中指定限定符(“自行车”)。所以明天我需要在服务类中将其更改为新的 implm,如限定符(“汽车”)。同样,如果有卡车,我需要创建扩展车辆的新类并在服务中用作限定符(“卡车”)。我仍然需要去上课并更改这 1 行代码。更改仍然是不可避免的。我实际上这样做有什么好处:
public interface Vehicle {
public void start();
public void stop();
}
@Component(value="car")
public class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void stop() {
System.out.println("Car stopped");
}
}
@Component(value="bike")
public class Bike implements Vehicle {
@Override
public void start() {
System.out.println("Bike started");
}
@Override
public void stop() {
System.out.println("Bike stopped");
}
}
@Component
public class VehicleService {
@Autowired
@Qualifier("bike")
private Vehicle vehicle;
public void service() {
vehicle.start();
vehicle.stop();
}
}
解决方案
推荐阅读
- python - 如何在kivy的tabbedpanel小部件中启用动态创建的选项卡的滚动?
- ios - 数据存在时,Swift firebase 快照返回 null
- elasticsearch - 如何获取字段的 doc_values 值?
- javascript - Google Sheets API 节点客户端库最小示例
- typescript - 打字稿。如果传递了属性 1,则需要属性 2
- c# - 如何在 ASP.NET Core 中本地化验证属性的标准错误消息
- php - 有没有办法检查回显文本值?
- apache-spark - 使用本地 Pyspark 从 GCS 打开镶木地板
- sql - 如何转换一列数组值
- python - 加载和评分之间的因子顺序不同(使用 oblimin 旋转),这怎么可能?