如何在Spring mvc中动态注入子类型依赖?

时间:2016-10-31 09:30:34

标签: spring-mvc

public class ManageVehicles{
    @Autowired
    Vehicle vehicle;
}

public inteface Vehicle{    
}

public class Ferrari implements Vehicle{    
}

public class Lamborghini implements Vehicle{    
}

public class Fiat implements Vehicle{    
}

public class Bmw implements Vehicle{    
}

从UI我选择车辆,所以我想从车辆对象的下拉列表中选择哪些车辆 应该注入ManageVehicles类中声明的'vehicle'变量。如何实现这个目标?

1 个答案:

答案 0 :(得分:0)

我认为你可以使用Vehicle Factory设计模式来做到这一点,根据你在VehicleFactory getVehicle中提供的参数,很容易返回车辆

public class VehicleFactory {


   public Vehicle getVehicle(String vehicleType){
      if(vehicleType == null){
         return null;
      }     
      if(vehicleType.equalsIgnoreCase("Ferrari")){
         return new Ferrari();

      } else if(vehicleType.equalsIgnoreCase("Lamborghini")){
         return new Lamborghini();

      } else if(vehicleType.equalsIgnoreCase("Fiat")){
         return new Fiat();
      }

      return null;
   }
}