Java 春天工厂如何获得豆子
我有以下代码:Java 春天工厂如何获得豆子,java,spring,Java,Spring,我有以下代码: public interface CreatorFactory<E extends Vehicle> { public VehicleType<E> getVehicle(); public boolean supports(String game); } public abstract AbstractVehicleFactory<E extends Vehicle> implements CreatorFactory
public interface CreatorFactory<E extends Vehicle> {
public VehicleType<E> getVehicle();
public boolean supports(String game);
}
public abstract AbstractVehicleFactory<E extends Vehicle> implements CreatorFactory {
public VehicleType<E> getVehicle() {
// do some generic init
getVehicle();
}
public abstract getVehicle();
public abstract boolean supports(String game);
}
公共接口创建者工厂{
公共车辆类型getVehicle();
公共布尔支持(字符串游戏);
}
公共抽象抽象车辆工厂实现CreatorFactory{
公共车辆类型getVehicle(){
//做一些泛型初始化
getVehicle();
}
公共抽象getVehicle();
公共抽象布尔支持(字符串游戏);
}
我有多个工厂,汽车,卡车等等
@Component
public CarFactory extends AbstractVehicleFactory<Car> {
/// implemented methods
}
@Component
public TruckFactory extends AbstractVehicleFactory<Truck> {
/// implemented methods
}
@组件
公共汽车厂{
///实施方法
}
@组成部分
公共卡车工厂扩展了抽象车辆工厂{
///实施方法
}
我想做的是将实现的工厂作为列表拉到一个单独的类中,但我不确定泛型在这种情况下是如何工作的。。。我知道在春天你可以得到所有特定类型的豆子。。。这还能用吗
使用擦除,我猜泛型类型将被删除 看起来您需要:
@Autowired
List<AbstractVehicleFactory> abstractVehicleFactories;
@Autowired
列出汽车制造厂;
首先,我认为可能没有必要获取bean列表。您只需要得到使用泛型类型声明的确切bean
在Spring framework中的BeanFactory接口中,有一种方法可用于满足您的需求:
public interface BeanFactory {
/**
* Return the bean instance that uniquely matches the given object type, if any.
* @param requiredType type the bean must match; can be an interface or superclass.
* {@code null} is disallowed.
* <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
* but may also be translated into a conventional by-name lookup based on the name
* of the given type. For more extensive retrieval operations across sets of beans,
* use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
* @return an instance of the single bean matching the required type
* @throws NoSuchBeanDefinitionException if there is not exactly one matching bean found
* @since 3.0
* @see ListableBeanFactory
*/
<T> T getBean(Class<T> requiredType) throws BeansException;
}
或者只需自动查看@Qualifier annotation for injection
@Component("carFactory")
public CarFactory extends AbstractVehicleFactory<Car> {
/// implemented methods
}
@Component("truckFactory ")
public TruckFactory extends AbstractVehicleFactory<Truck> {
/// implemented methods
}
公共抽象getVehicle()的返回类型;
@Component("carFactory")
public CarFactory extends AbstractVehicleFactory<Car> {
/// implemented methods
}
@Component("truckFactory ")
public TruckFactory extends AbstractVehicleFactory<Truck> {
/// implemented methods
}
@Qualifier("carFactory")
@Autowired
private CarFactory carFactory ;
@Qualifier("truckFactory")
@Autowired
private TruckFactory TruckFactory;