-1

我有以下代码:

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);

}

我有多家工厂,用于汽车、卡车等。

@Component
public CarFactory extends AbstractVehicleFactory<Car> {

   /// implemented methods

}

@Component
public TruckFactory extends AbstractVehicleFactory<Truck> {

   /// implemented methods

}

我想做的是将实现的工厂作为一个列表拉到一个单独的类中,但我不确定泛型在这种情况下是如何工作的......我知道在春天你可以获得特定类型的所有bean......这会不会还上班吗?...

通过擦除,我猜泛型类型将被删除.. ??

4

2 回答 2

1

首先,我认为可能不需要获取 bean 列表。而且您只想获得使用泛型类型声明的确切 bean。

在 Spring 框架的 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;
}

您可以使用如下代码:

Car carFactory = applicationContext.getBean( CarFactory.class );
Trunk trunkFactory = applicationContext.getBean( TrunkFactory.class );

或者只是查看@Qualifier 注解自动注入。

@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;
于 2013-03-04T13:58:31.403 回答
0

看起来你需要:

@Autowired
List<AbstractVehicleFactory> abstractVehicleFactories;
于 2013-03-04T13:22:04.627 回答