2013-03-04 75 views
0

我有以下代码:春季如何让豆在工厂

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

} 

和我有多个工厂,汽车,truck..etc ..

@Component 
public CarFactory extends AbstractVehicleFactory<Car> { 

    /// implemented methods 

} 

@Component 
public TruckFactory extends AbstractVehicleFactory<Truck> { 

    /// implemented methods 

} 

我想要做的是把实施的工厂作为一个单独的类来列表,但我不知道泛型在这种情况下是如何工作的......我知道在春天你可以得到所有特定类型的bean ......这仍然有效吗? ..

有删除,我猜泛型将被删除.. ??

+0

哪个公共抽象getVehicle的返回类型(); – psabbate 2013-03-04 13:24:02

回答

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

看起来像你需要:

@Autowired 
List<AbstractVehicleFactory> abstractVehicleFactories;