春天如何在工厂里获得豆子

时间:2013-03-04 13:14:26

标签: 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 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。这还能用吗?...

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

看起来你需要:

@Autowired
List<AbstractVehicleFactory> abstractVehicleFactories;