【问题标题】:In Spring, how to declare a bean with the prototype scope?在 Spring 中,如何声明一个具有原型作用域的 bean?
【发布时间】:2013-08-05 20:20:45
【问题描述】:

在Spring中,如何声明一个具有原型作用域的bean?默认情况下,Spring IOC 中的 bean 会在单例范围内自动初始化。

【问题讨论】:

    标签: spring


    【解决方案1】:
    <bean id="your id" class="your class" scope="prototype" />
    

    或者用@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)标记你正在使用的注解

    【讨论】:

    • 感谢您的及时回复。
    • 当然,我需要试一试。
    【解决方案2】:

    除了@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE),我们还可以简单写成@Scope("prototype")。还有几种方法可用于以编程方式创建 bean 并设置它们的范围。例如:SingletonBeanRegistry'sregisterSingletonBeanDefinition'ssetScope

    这是一个简单的例子,我们注册一个自定义 bean 并使用setScope 设置它的范围:

    package com.zetcode;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.support.BeanDefinitionBuilder;
    import org.springframework.beans.factory.support.BeanDefinitionRegistry;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.annotation.ComponentScan;
    
    @ComponentScan(basePackages = "com.zetcode")
    public class Application {
    
        private static final Logger logger = LoggerFactory.getLogger(Application.class);
    
        public static void main(String[] args) {
    
            var ctx = new AnnotationConfigApplicationContext(Application.class);
    
            var beanFactory = (BeanDefinitionRegistry) ctx.getBeanFactory();
    
            beanFactory.registerBeanDefinition("myBean",
                    BeanDefinitionBuilder.genericBeanDefinition(String.class)
                            .addConstructorArgValue("This is my bean")
                            .setScope("prototype")
                            .getBeanDefinition()
            );
    
            logger.info("{}", ctx.getBean("myBean"));
    
            ctx.close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 2015-11-26
      • 2021-01-13
      • 2019-02-27
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      相关资源
      最近更新 更多