首页 > 解决方案 > 为什么注入 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();
    }
}

标签: springspring-boot

解决方案


这是因为 spring 不知道您何时说需要车辆天气实例来为您提供自行车或汽车,@Qualifier 有助于通知 spring 您需要特定的。

如果您不关心您想要在 VehicleService 中使用哪一个,那么您可以使用@Primary将其中一个标记为主要的,以便 spring 可以解决冲突

或者,将 Vehicle 作为 VehicleService 中的列表,然后从列表中选择合适的需要的,您可以使用@Order注释对列表中的值进行排序。您可以使用 @PostConstruct 注释来编写要拾取哪个值的逻辑。


推荐阅读