What is difference between singleton and prototype bean?

前端 未结 9 1852
攒了一身酷
攒了一身酷 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: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

    
                                                            
提交回复
热议问题