• 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;
    }
  • 相关阅读:
    Windows下建立FTP服务器站点
    Markdown语法指南
    Win7系统修改hosts无法保存怎么办?
    PHP 7 错误处理 Error
    strtotime 的 BUG
    三角箭头 css实现
    关于 layer.open 动态赋值不了的问题
    layui layer.open弹出框获取不了 input框的值
    webhook 自动部署代码
    lnmp 命令 及其 TP5 部署遇到的一些问题
  • 原文地址:https://www.cnblogs.com/shamgod/p/5231461.html
Copyright © 2020-2023  润新知