What is difference between singleton and prototype bean?

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

    Let's just simply look this up through code.

    Following is a TennisCoach Bean with default singleton Scope

    @Component
    @Scope("singleton")
    public class TennisCoach implements Coach {
    
        public TennisCoach(){
    
        }
    
        @Autowired
        public void setFortuneService(FortuneService fortuneService) {
            this.fortuneService = fortuneService;
        }
    
        @Override
        public String getDailyWorkout() {
            return "Practice your backhand volley";
        }
    
        @Override
        public String getDailyFortune() {
            return "Tennis Coach says : "+fortuneService.getFortune();
        }
    
    }
    

    Following is a TennisCoach Bean with prototype scope

    @Component
    @Scope("prototype")
    public class TennisCoach implements Coach {
    
        public TennisCoach(){
            System.out.println(">> TennisCoach: inside default constructor");
        }
    
        @Autowired
        public void setFortuneService(FortuneService fortuneService) {
            System.out.println(">> Tennis Coach: inside setFortuneService");
            this.fortuneService = fortuneService;
        }
    
        @Override
        public String getDailyWorkout() {
            return "Practice your backhand volley";
        }
    
        @Override
        public String getDailyFortune() {
            return "Tennis Coach says : "+fortuneService.getFortune();
        }
    
    }
    

    Following is a Main class :

    public class AnnotationDemoApp {
    
        public static void main(String[] args) {
    
    
            // read spring config file
            ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");
    
           // get the bean from the spring container
           Coach theCoach = context.getBean("tennisCoach",Coach.class);
           Coach alphaCoach = context.getBean("tennisCoach",Coach.class);
           // call a method on the bean
           System.out.println("Are the two beans same :" + (theCoach==alphaCoach));
    
           System.out.println("theCoach : " + theCoach);
           System.out.println("alphaCoach: "+ alphaCoach);
    
    
           context.close()
    
        }
    }
    

    For singleton scope the output is :

    Are the two beans same :true
    theCoach : com.springdemo.TennisCoach@2a53142
    alphaCoach: com.springdemo.TennisCoach@2a53142
    

    For prototype scope the output is :

    Are the two beans same :false
    theCoach : com.springdemo.TennisCoach@1b37288
    alphaCoach: com.springdemo.TennisCoach@1a57272
    

提交回复
热议问题