michaldo
michaldo

Reputation: 4609

How to get bean id within factory method?

Configuration

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

Code:

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

How to print out ford ?

Upvotes: 1

Views: 471

Answers (2)

michaldo
michaldo

Reputation: 4609

reos' solution is working, but I cannot accept duplication so I applied other solution

Configuration

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

Code

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);
    }
    (...)
}

Upvotes: 0

reos
reos

Reputation: 8324

factory-method is used to create an object, it replace the constructor call. When yo tell Spring factory-method="createCar" you're telling that it needs to call createCar in order to create the bean ford.

createCar method prints the name of the car but the properties are not been set already so it should be printing null.

I would recommend you to use constructor-arg in order to pass arguments to the createCar method.

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

And

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

Upvotes: 2

Related Questions