2013-03-04 89 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;