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;
    }
  • 相关阅读:
    在CentOS7上部署Kubernetes集群
    使用Ansible部署etcd 3.2高可用集群
    shiro框架学习-3- Shiro内置realm
    shiro框架学习-2-springboot整合shiro及Shiro认证授权流程
    shiro框架学习-1-shiro基本概念
    markdown编辑器常用命令
    华为云服务器centos7.3安装tomcat
    华为云服务器centos7.3 安装jdk
    springboot2.0+mysql整合mybatis,发现查询出来的时间比数据库datetime值快了8小时
    使用IDEA自动生成Java实体类
  • 原文地址:https://www.cnblogs.com/shamgod/p/5231461.html
Copyright © 2011-2022 走看看