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;
    }
  • 相关阅读:
    2008新的一年到来了!
    WPF 回车转Tab实现跳转
    Remoting和WebService/Ref, Out, Params的区别/
    教你如何编写游戏外挂
    在表达式中使用内置报表函数和聚合函数 (Reporting Services)
    Facade模式
    十分经典的批处理教程
    Entity Framework(实体框架)之详解 Linq To Entities 之一 (经典收集自用)
    关于AppDomain 创建实例进行程序集之间的通讯问题
    OPENQUERY用法
  • 原文地址:https://www.cnblogs.com/shamgod/p/5231461.html
Copyright © 2011-2022 走看看