zoukankan      html  css  js  c++  java
  • SPRING IN ACTION 第4版笔记-第二章-003-以Java形式注入Bean、@Bean的用法

    1.

    package soundsystem;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class CDPlayerConfig {
      
      @Bean
      public CompactDisc compactDisc() {
        return new SgtPeppers();
      }
      
      @Bean
      public CDPlayer cdPlayer(CompactDisc compactDisc) {
        return new CDPlayer(compactDisc);
      }
    
    }

    The @Bean annotation tells Spring that this method will return an object that should
    be registered as a bean in the Spring application context. The body of the method
    contains logic that ultimately results in the creation of the bean instance.
    By default, the bean will be given an ID that is the same as the @Bean -annotated
    method’s name. In this case, the bean will be named compactDisc . If you’d rather it
    have a different name, you can either rename the method or prescribe a different
    name with the name attribute:

    2.可以指定bean名称

    @Bean(name="lonelyHeartsClubBand")
    public CompactDisc sgtPeppers() {
    return new SgtPeppers();
    }

    3.利用@Bean根据条件注入不同的依赖

    @Bean
    public CompactDisc randomBeatlesCD() {
    int choice = (int) Math.floor(Math.random() * 4);
    if (choice == 0) {
    return new SgtPeppers();
    } else if (choice == 1) {
    return new WhiteAlbum();
    } else if (choice == 2) {
    return new HardDaysNight();
    } else {
    return new Revolver();
    }
    }

    4.表面上似乎是调用同一个配置文件的函数

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

    这种配置表面上似乎是调用同一个配置文件的函数,但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.

    5.spring会自动找id为“compactDisc”的bean注入

    @Bean
    public CDPlayer cdPlayer(CompactDisc compactDisc) {
    return new CDPlayer(compactDisc);
    }

    6.不但可以通过构造函数,也可通过set访求注入

    @Bean
    public CDPlayer cdPlayer(CompactDisc compactDisc) {
    CDPlayer cdPlayer = new CDPlayer(compactDisc);//这里的构造函数是不是不用传参数????
    cdPlayer.setCompactDisc(compactDisc);
    return cdPlayer;
    }
  • 相关阅读:
    IOS总结_IOS经常使用的方法集合、调用系统电话、设备区分、APP内永不锁屏
    huffman编码——原理与实现
    python字典构造函数dict(mapping)解析
    tomcat配置sqlserver数据库
    Tomcat全攻略
    第一次QQ群视频教育有感
    UIControl-IOS开发
    java内存分析总结
    Android笔记 之 旋转木马的音乐效果
    Android中API建议的方式实现SQLite数据库的增、删、改、查的操作
  • 原文地址:https://www.cnblogs.com/shamgod/p/5231461.html
Copyright © 2011-2022 走看看