Brady Zhu
Brady Zhu

Reputation: 1405

In Spring, how to declare a bean with the prototype scope?

In Spring, how to declare a bean with the prototype scope? By default, beans in Spring IOC are initialized automatically with the scope of singleton.

Upvotes: 2

Views: 1571

Answers (2)

Jan Bodnar
Jan Bodnar

Reputation: 11647

In addition to @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE), we can also simply write @Scope("prototype"). There are also several methods for programmatic creation of beans and setting their scopes. For instance: SingletonBeanRegistry's registerSingleton or BeanDefinition's setScope.

Here is a simple example where we register a custom bean and set its scope with 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();
    }
}

Upvotes: 0

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18403

<bean id="your id" class="your class" scope="prototype" />

or mark with @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) your are using annotation

Upvotes: 6

Related Questions