五、原型设计模式(Prototype Pattern)
5.1 介绍
相比单例设计模式,原型模式是每次创建一个对象,下面看下spring是如何使用原型模式的
5.2 Spring中原型bean的创建
创建原型bean需要在xml特别说明:
<bean id="hello" class="com.zlx.demo.Hello" scope="prototype"/>
protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException { final String beanName = transformedBeanName(name);
Object bean; // Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) {
...
} else {
... try {
... // Create bean instance.
if (mbd.isSingleton()) {
...
} //创建原型bean
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);
} else {
...
}
} catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName); throw ex;
}
}
... return (T) bean;
}
createBean函数里面则是根据bean定义创建新bean,感兴趣的可以看看。
5.3 使用场景
当有业务场景使用某个bean时候需要使用自己的一个拷贝的时候使用。