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

  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    PoolMember 用法
    pool 提供的方法
    F5 VirtualServer 提供的方法
    入职两年,我和业务撕了108次逼
    C 语言编程 — 函数
    C 语言编程 — 逻辑控制语句
  • 原文地址:https://www.cnblogs.com/shamgod/p/5231469.html
Copyright © 2011-2022 走看看