如何在工厂方法中获取bean id?

时间:2015-12-16 15:05:45

标签: spring

配置

<bean id="carFactory" class="CarFactory" />
<bean id="ford" factory-bean="carFactory" factory-method="createCar"/>

代码:

public class CarFactory implements BeanNameAware {

    public String beanName;

    @Override public void setBeanName(String name) { beanName = name;}

    public Car createCar() {
        System.out.println(beanName); // prints carFactory
        return new Car();
    } 
}

如何打印 ford

2 个答案:

答案 0 :(得分:2)

factory-method用于创建对象,它替换构造函数调用。当你告诉Spring factory-method =&#34; createCar&#34;你告诉它需要调用createCar才能创建bean ford。

createCar方法打印汽车的名称,但尚未设置属性,因此应该打印为null。

我建议你使用constructor-arg将参数传递给createCar方法。

<bean id="ford" factory-bean="carFactory" factory-method="createCar">
    <constructor-arg value="ford"/>
</bean>

public Car createCar(String beanName) {
    System.out.println(beanName); // prints carFactory
    return new Car();
} 

答案 1 :(得分:0)

稀土氧化物&#39;解决方案正在运行,但我无法接受重复,所以我应用了其他解决方案

配置

<bean id="carFactory" class="CarFactory" />
<bean id="ford" class="CarProducer"/>

代码

public class CarProducer extends AbstractFactoryBean<Car> implements BeanNameAware {
    public String carName;

    @Override public void setBeanName(String name) { carName= name;}

    @Autowired private CarFactory factory;

    @Override protected Car createInstance() throws Exception {
        System.out.println(carName); // prints ford
        return factory.createCar(carName);
    }
    (...)
}