zoukankan      html  css  js  c++  java
  • SPRING IN ACTION 第4版笔记-第二章-004-Bean是否单例

    spring的bean默认是单例,加载容器是会被化,spring会拦截其他再次请求bean的操作,返回spring已经创建好的bean.

    It appears that the CompactDisc is provided by calling sgtPeppers , but that’s not
    exactly true. Because the sgtPeppers() method is annotated with @Bean , Spring will
    intercept any calls to it and ensure that the bean produced by that method is returned
    rather than allowing it to be invoked again.
    For example, suppose you were to introduce another CDPlayer bean that is just
    like the first:

    @Bean
    public CompactDisc sgtPeppers() {
    return new SgtPeppers();
    }
    
    @Bean
    public CDPlayer cdPlayer() {
    return new CDPlayer(sgtPeppers());
    }
    @Bean
    public CDPlayer anotherCDPlayer() {
    return new CDPlayer(sgtPeppers());
    }

    If the call to sgtPeppers() was treated like any other call to a Java method, then each

    CDPlayer would be given its own instance of SgtPeppers . That would make sense if we
    were talking about real CD players and compact discs. If you have two CD players,
    there’s no physical way for a single compact disc to simultaneously be inserted into
    two CD players.
    In software, however, there’s no reason you couldn’t inject the same instance of
    SgtPeppers into as many other beans as you want. By default, all beans in Spring are
    singletons, and there’s no reason you need to create a duplicate instance for the sec-
    ond CDPlayer bean. So Spring intercepts the call to sgtPeppers() and makes sure
    that what is returned is the Spring bean that was created when Spring itself called
    sgtPeppers() to create the CompactDisc bean. Therefore, both CDPlayer beans will
    be given the same instance of SgtPeppers

  • 相关阅读:
    构建一个应用,并在docker compose里运行起来
    docker engine docker-compose部署
    django 返回数据的几种常用姿势
    fiddler+httprunner 零编码实现接口自动化DEMO
    选择排序
    曾经学的那些表示时间复杂度的公式怎么来的?
    python+Airtest+android使用AirtestIDE编写一个DEMO
    怎么计算时间复杂度?
    算法_冒泡排序python+java实现
    2020年1月16日(多进程)
  • 原文地址:https://www.cnblogs.com/shamgod/p/5231469.html
Copyright © 2011-2022 走看看