遵循原型设计模式的Spring原型 [英] Spring prototype following prototype design pattern

查看:158
本文介绍了遵循原型设计模式的Spring原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring将bean范围提供为原型".意味着每当应用程序需要bean时,Spring容器都会创建一个bean的新实例. 是否也遵循原型设计模式? 它是否仅创建对象一次,并且在随后的请求中对创建的对象调用clone()方法来创建新对象?

Spring provides bean scope as "Prototype". Means whenever bean is required in application, Spring container will create a fresh/new instance of bean. Does is follow prototype design pattern also? Does it create object only once and in subsequent request calls clone() method on created object to create new object?

如果有人可以提供JDK,Spring,Hibernate或任何J2EE框架中的原型示例,那么

Also if someone can provide example of prototype in JDK, Spring, Hibernate or any J2EE framework.

推荐答案

没有spring不使用克隆来创建原型范围内的实例.

No spring does not use cloning to create prototype scoped instances.

下面是摘自AbstractBeanFactory.doGetBean()函数的代码段:

Below is the code snippet taken from AbstractBeanFactory.doGetBean() function:

// 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方法调用可归结为以下代码:

The createBean method call boils down to below code:

BeanUtils.instantiateClass(constructorToUse);

这篇关于遵循原型设计模式的Spring原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆