首页 文章

在Spring上下文中的原型bean中的单例bean

提问于
浏览
0

通常在Spring Context中,如果在单例bean中注入原型bean,则父类的属性将覆盖原型bean范围 . 但是,如果在原型bean范围中注入单例范围bean,将会发生什么 . 仍然使用内部bean的get bean将返回内部bean的新实例?

2 回答

  • 0

    不, prototype bean的所有实例都将共享 singleton bean的相同实例 .
    示例: ``
    `@Service
    public class SingletonBean {
    private int id;
    private static int static_id = 0;

    public SingletonBean() {
        id = static_id++;
    }
    
    @Override
    public String toString() {
        return "SingletonBean [id=" + id + "]";
    }
    

    }`` ``@Service
    @Scope("prototype")
    public class PrototypeBean {

    @Autowired
    private SingletonBean singletonBean;
    private int id;
    
    private static int static_id = 0;
    
    public PrototypeBean() {
        id = static_id++;
    }
    
    @Override
    public String toString() {
        return "id=" + id + ", PrototypeBean [singletonBean=" + singletonBean + "]";
    }
    

    }`

    ``

    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
            PrototypeBean beanA = context.getBean(PrototypeBean.class);
            PrototypeBean beanB = context.getBean(PrototypeBean.class);
    
            System.out.println(beanA); //id=0, PrototypeBean [singletonBean=SingletonBean [id=0]]
            System.out.println(beanB); //id=1, PrototypeBean [singletonBean=SingletonBean [id=0]]
        }
    }
    
    </code>
    
  • 0

    通常在Spring上下文中,如果在单例bean中注入原型bean,则父类的属性将覆盖原型bean范围 .

    这是真的,但并非总是如此,您可以使用Lookup方法注入覆盖它,这使您能够在每个请求中注入新的原型对象,检查documentation以获取有关它的完整示例,

    对于你的主要问题,单例是在加载上下文时创建的,然后无论是谁调用这个单例,上下文都给出相同的实例,而不考虑谁进行调用

相关问题