What is difference between singleton and prototype bean?

前端 未结 9 1810
攒了一身酷
攒了一身酷 2020-11-30 00:18

i\'m new to spring and i read this :

Basically a bean has scopes which defines their existence on the application

Singleton: means single bean def

相关标签:
9条回答
  • 2020-11-30 01:06

    Adding to the above..dont get confuse with the java singleton. according to JAVA spec singleton means only one instance of that bean will be created per JVM. but in spring singleton means one instance for that particular bean will be created per application context. so if your app has more than one context you can still have more than one instance for that bean.

    0 讨论(0)
  • 2020-11-30 01:09

    Prototype scope = A new object is created each time it is injected/looked up. It will use new SomeClass() each time.

    Singleton scope = (Default) The same object is returned each time it is injected/looked up. Here it will instantiate one instance of SomeClass and then return it each time.

    See also:

    • Spring Bean Scopes
    0 讨论(0)
  • 2020-11-30 01:12
    1. Singleton scope is default.
    2. Singleton beans are created during initialization of app context and same bean is returned always.
    3. Prototype bean is created when ever it is called. Each time it is called we get a new object.

    Note : Bean with any scope will be created if it is referred by other beans and called using Application context.

    Example code to check this.

    public class PrototypeClass {
    
            PrototypeClass()
            {
                System.out.println("prototype class is created"+this.toString());
            }
    
        }
    

    This will print the relevant text when constructor is invoked.

    for the below code

    for(int i=0;i<10;i++) {
       PrototypeClass pct= (PrototypeClass) context.getBean("protoClass");
    }
    

    prototype class is createdSpring.PrototypeClass@29774679 prototype class is createdSpring.PrototypeClass@3ffc5af1 prototype class is createdSpring.PrototypeClass@5e5792a0 prototype class is createdSpring.PrototypeClass@26653222 prototype class is createdSpring.PrototypeClass@3532ec19 prototype class is createdSpring.PrototypeClass@68c4039c prototype class is createdSpring.PrototypeClass@ae45eb6 prototype class is createdSpring.PrototypeClass@59f99ea prototype class is createdSpring.PrototypeClass@27efef64 prototype class is createdSpring.PrototypeClass@6f7fd0e6 prototype class is createdSpring.PrototypeClass@47c62251

    Bean definition is

    <bean id="protoClass" class="Spring.PrototypeClass" scope="prototype</bean>
    

    Now I changed the scope in bean definition to singleton . Constructor is called only once during initialization of context. Next I removed the scope attribute and observed same behavior as singleton.

    0 讨论(0)
提交回复
热议问题