【问题标题】:Why do Injecting bean still needs code change?为什么注入 bean 仍然需要更改代码?
【发布时间】:2020-07-31 10:42:21
【问题描述】:

我是 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();
    }
}

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 2017-10-15
      • 2014-06-19
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多