Spring原型(prototype)遵循原型(prototype)设计模式

标签 spring design-patterns prototype-pattern

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/

相关文章:

java - 如何在 Spring MVC Web 应用程序中更新 session 属性

java - Java 中的设计模式,哪些是研究其应用程序的最佳开源项目?

design-patterns - 原型(prototype)设计模式示例(C++)

java - 公共(public)代码的父类(super class)与实用程序类

spring - 如何将 StatelessSession 与 Spring Data JPA 和 Hibernate 一起使用?

javascript - ES6 获取 : How do I change the localhost port it calls?

java - 类实例直接协同工作

design-patterns - DDD - 没有域服务的条件业务规则

design-patterns - 原型(prototype)设计模式真的只是克隆吗?