我正在尝试实现FactoryBean。这是我的代码:
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;
}
}
以下是我声明我的 bean 的方式:
<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>
当我从上下文中获取这些 bean 时,我看到我得到了不同的 bean,尽管我将对象声明为单例。
我正在尝试了解 FactoryBean,但我知道这不是一个有效的用例,而且是设计上的一个错误。但我想知道它为什么会这样?有人可以解释一下吗?