Spring 将 bean 范围提供为“原型(prototype)”。意味着每当应用程序需要 bean 时,Spring 容器将创建一个新的/新的 bean 实例。
是否也遵循原型(prototype)设计模式?
它是否只创建一次对象并在随后的请求中调用已创建对象的 clone() 方法来创建新对象?
此外,如果有人可以提供 JDK、Spring、Hibernate 或任何 J2EE 框架中的原型(prototype)示例。
最佳答案
没有 spring 不使用克隆来创建原型(prototype)作用域实例。
下面是从 AbstractBeanFactory.doGetBean() 函数中获取的代码片段:
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
createBean 方法调用归结为以下代码:
BeanUtils.instantiateClass(constructorToUse);
关于Spring原型(prototype)遵循原型(prototype)设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26609980/