I am trying to implement FactoryBean. Here is my code:
public class SkilledEmployee extends AbstractFactoryBean<Employee> {
private Employee emp;
private Skill skill;
public SkilledEmployee(Employee emp, Skill skill) {
this.emp = emp;
this.skill = skill;
}
public Class<Employee> getObjectType() {
return Employee.class;
}
protected Employee createInstance() throws Exception {
Employee emp1 = new Employee(emp);
emp1.addSkill(skill);
return emp1;
}
public boolean isSingleton() {
return true;
}
}
And here is how I declared my beans:
<bean id="skilledEmployee1" class="com.pramati.spring.SkilledEmployee">
<constructor-arg ref="subordinate3"/>
<constructor-arg ref="singing"/>
</bean>
<bean id="skilledEmployee2" class="com.pramati.spring.SkilledEmployee">
<constructor-arg ref="subordinate2"/>
<constructor-arg ref="singing"/>
</bean>
When I get these beans from context, I see that I am getting different beans though I declared the object to be singleton.
I am trying to understand FactoryBean and I know that this is not a valid usecase and it’s a blunder in design. But I wanted to know why it is behaving like this? Can someone please explain?
These are two disctinct beans because you declared them separately. Simpler example:
Here we declared two singleton beans,
foo1andfoo2. If you fetch them from Spring, you will get two different objects. However if you fetch them again, you’ll get the same object.Similarilly in your case:
skilledEmployee1andskilledEmployee2are two distinct, singleton beans. If you get them from the context again, you’ll receive the same instance – as expected.