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

  • 相关阅读:
    PAT (Basic Level) Practise 1013 数素数
    PAT (Basic Level) Practise 1014 福尔摩斯的约会
    codeforces 814B.An express train to reveries 解题报告
    KMP算法
    rsync工具
    codeforces 777C.Alyona and Spreadsheet 解题报告
    codeforces 798C.Mike and gcd problem 解题报告
    nginx + tomcat多实例
    MongoDB副本集
    指针的艺术(转载)
  • 原文地址:https://www.cnblogs.com/shamgod/p/5231469.html
Copyright © 2011-2022 走看看