Spring Bean Scopes

前端 未结 9 1764
说谎
说谎 2020-11-29 18:25

Can someone explain what the scopes are in Spring beans I\'ve always just used \'prototype\' but are there other parameters I can put in place of that?

Example of wh

9条回答
  •  眼角桃花
    2020-11-29 18:45

    A short example what is the difference between @Scope("singleton") (default) and @Scope("prototype"):

    DAO class:

    package com.example.demo;
    
    public class Manager {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    Configuration:

    @Configuration
    public class AppConfiguration {
        @Bean
        @Scope("singleton")
        public Manager getManager(){
            return new Manager();
        }
    }
    

    and MainApp:

    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
            context.scan("com.example.demo");
            context.refresh();
    
            Manager firstManager = context.getBean(Manager.class);
            firstManager.setName("Karol");
    
            Manager secondManager = context.getBean(Manager.class);
            System.out.println(secondManager.getName());
        }
    
    }
    

    In this example the result is: Karol even if we set this name only for firstManager object. It's because Spring IoC container created one instance of object. However when we change scope to @Scope("prototype") in Configuration class then result is: null because Spring IoC container creates a new bean instance of the object when request for that bean is made.

提交回复
热议问题