Spring 装配Bean详解

一、简介

​ Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的关系。Spring具有非常大的灵活性,它提供了三种主要的装配机制:

  • 在XML中进行显示配置;
  • 在Java中进行显示配置;
  • 隐式的bean发现机制和自动装配。

二、在XML中进行显示配置

1. 声明一个简单的bean

1. 创建CD接口

public interface CompactDisc {void play();
}

2. 创建NowAndThen类

public class NowAndThen implements CompactDisc{private String title = "Now And Then.";private String artist = "The Beatles";@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);}}

3. 在bean.xml文件中配置

<!--  通过class属性来声明一个简单的bean,此时因为没有指定ID,bean的ID将会是com.shiftycat.soundsystem.NowAndThen#0  -->
<bean class="com.shiftycat.soundsystem.NowAndThen"/>
<!--  使用id属性可以用来指定ID  -->
<bean id="CompactDisc" class="com.shiftycat.soundsystem.NowAndThen"/>

4. 进行测试

@Test
public void compactDiscTest() {ClassPathXmlApplicationContext classPathXmlApplicationContext =new ClassPathXmlApplicationContext("bean.xml");CompactDisc compactDisc = classPathXmlApplicationContext.getBean(CompactDisc.class);compactDisc.play();
}

5. 测试结果

Playing Now And Then. by The Beatles

2. 借助构造器注入初始化bean

​ 构造器注入有两种方案:

  • constructor-arg元素
  • 使用Spring 3.0所引入的c-命名空间

1. 创建CD接口

public interface CompactDisc {void play();
}

2. 创建NowAndThen类

public class NowAndThen implements CompactDisc{private String title = "Now And Then.";private String artist = "The Beatles";@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);}}

3. 创建MediaPlayer接口

public interface MediaPlayer {void play();
}

4. 创建CDPlayer类

public class CDPlayer implements MediaPlayer{private CompactDisc cd;// 构造器注入public CDPlayer(CompactDisc cd) {this.cd = cd;}@Overridepublic void play() {System.out.println("Loading...");cd.play();}
}

5. 在bean.xml文件中配置

<bean id="CompactDisc" class="com.shiftycat.soundsystem.NowAndThen"/>\
<!--  第一种配置方案:`constructor-arg`元素  -->
<bean id="cdPlayer" class="com.shiftycat.soundsystem.CDPlayer"><constructor-arg ref="CompactDisc"/>
</bean>
<!--  第二种配置方案:使用Spring 3.0所引入的c-命名空间  -->
<!--  c:构造器参数名-ref=“要注入的bean的ID”  -->
<bean id="cdPlayer" class="com.shiftycat.soundsystem.CDPlayer" c:cd-ref="CompactDisc"/>
<!--  或者将参数的名称替换为"_0"或者"_"  -->
<bean id="cdPlayer" class="com.shiftycat.soundsystem.CDPlayer" c:_0-ref="CompactDisc" />
<bean id="cdPlayer" class="com.shiftycat.soundsystem.CDPlayer" c:_-ref="CompactDisc" />

6. 进行测试

@Test
public void cdPlayerTest() {ClassPathXmlApplicationContext classPathXmlApplicationContext =new ClassPathXmlApplicationContext("bean.xml");CDPlayer cdPlayer = classPathXmlApplicationContext.getBean(CDPlayer.class);cdPlayer.play();}

7. 测试结果

Loading...
Playing Now And Then. by The Beatles
将字面量注入到构造器中

1. 创建BlackDisc类

public class BlackDisc implements CompactDisc{private String title;private String artist;public BlackDisc(String title, String artist) {this.title = title;this.artist = artist;}@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);}
}

2. 在bean.xml中进行配置

<bean id="blackDisc" class="com.shiftycat.soundsystem.BlackDisc"><constructor-arg value="Now And Then." /><constructor-arg value="The Beatles" />
</bean><bean id="blackDisc" class="com.shiftycat.soundsystem.BlackDisc"c:title="Now And Then."c:artist="The Beatles"
/><bean id="blackDisc" class="com.shiftycat.soundsystem.BlackDisc"c:_0="Now And Then."c:_1="The Beatles"
/>

3. 进行测试

@Test
public void blackDiscTest() {ClassPathXmlApplicationContext classPathXmlApplicationContext =new ClassPathXmlApplicationContext("bean.xml");BlackDisc blackDisc = classPathXmlApplicationContext.getBean(BlackDisc.class);blackDisc.play();
}

4. 测试结果

Playing Now And Then. by The Beatles

P.S. 装配集合

public class BlackDisc implements CompactDisc {private String title;private String artist;private List<String> tracks;public BlackDisc(String title, String artist, List<String> tracks) {this.title = title;this.artist = artist;this.tracks = tracks;}@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);for (String track : tracks) {System.out.println("-Track: " + track);}}
}
<bean id="blackDisc" class="com.shiftycat.soundsystem.BlackDisc"><constructor-arg value="Now And Then." /><constructor-arg value="The Beatles" /><constructor-arg><list><value>I know it's true</value><value>It's all because of you</value><value>And if I make it through</value><value>It's all because of you</value><value>And now and then</value></list></constructor-arg>
</bean>
Playing Now And Then. by The Beatles
-Track: I know it's true
-Track: It's all because of you
-Track: And if I make it through
-Track: It's all because of you
-Track: And now and then

3. 设置属性初始化bean

一般而言,对于强依赖使用构造器注入,对可选性的依赖使用属性注入。

1. 在CDPlayer类中设置setter方法

public class CDPlayer implements MediaPlayer{private CompactDisc cd;public void setCompactDisc(CompactDisc cd) {this.cd = cd;}@Overridepublic void play() {System.out.println("Loading...");cd.play();}
}

2. 在bean.xml文件中进行配置

<!--  可以使用property进行配置-->
<bean id="cdPlayer" class="com.shiftycat.soundsystem.CDPlayer"><property name="compactDisc" ref="compactDisc"/>
</bean>
<!--  或者使用p-命名空间性配置-->
<bean id="cdPlayer" class="com.shiftycat.soundsystem.CDPlayer"p:compactDisc-ref="compactDisc"/>

3. 进行测试

@Test
public void cdPlayerTest() {ClassPathXmlApplicationContext classPathXmlApplicationContext =new ClassPathXmlApplicationContext("bean.xml");CDPlayer cdPlayer = classPathXmlApplicationContext.getBean(CDPlayer.class);cdPlayer.play();
}

4. 测试结果

Loading...
Playing Now And Then. by The Beatles
将字面量注入到属性中

1. 在WhiteDisc类中设置setter方法

public class WhiteDisc implements CompactDisc{private String title;private String artist;private List<String> tracks;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getArtist() {return artist;}public void setArtist(String artist) {this.artist = artist;}public List<String> getTracks() {return tracks;}public void setTracks(List<String> tracks) {this.tracks = tracks;}@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);for (String track : tracks) {System.out.println("-Track: " + track);}}
}

2. 在bean.xml文件中进行配置

<bean id="whileDisc" class="com.shiftycat.soundsystem.WhiteDisc"><property name="artist" value="Now And Then."/><property name="title" value="The Beatles" /><property name="tracks"><list><value>I know it's true</value><value>It's all because of you</value><value>And if I make it through</value><value>It's all because of you</value><value>And now and then</value></list></property>
</bean>
<!--或者-->
<bean id="whileDisc" class="com.shiftycat.soundsystem.WhiteDisc"p:artist="Now And Then."p:title="The Beatles"><property name="tracks"><list><value>I know it's true</value><value>It's all because of you</value><value>And if I make it through</value><value>It's all because of you</value><value>And now and then</value></list></property>
</bean>
<!--或者-->
<bean id="whileDisc" class="com.shiftycat.soundsystem.WhiteDisc"p:artist="Now And Then."p:title="The Beatles"p:tracks-ref="tracks"
>
</bean><util:list id="tracks"><value>I know it's true</value><value>It's all because of you</value><value>And if I make it through</value><value>It's all because of you</value><value>And now and then</value>
</util:list>

3. 进行测试

@Test
public void whiteDiscTest() {ClassPathXmlApplicationContext classPathXmlApplicationContext =new ClassPathXmlApplicationContext("bean.xml");WhiteDisc whiteDisc = classPathXmlApplicationContext.getBean(WhiteDisc.class);whiteDisc.play();
}

4. 测试结果

Playing The Beatles by Now And Then.
-Track: I know it's true
-Track: It's all because of you
-Track: And if I make it through
-Track: It's all because of you
-Track: And now and then

三、在Java中进行显式配置

1. 声明简单的bean

1. 创建配置类

@Configuration
public class CDPlayerConfig {}

2. 声明简单的bean

@Configuration
public class CDPlayerConfig {@Beanpublic CompactDisc nowAndThen() {return new nowAndThen();}}

2. 借助JavaConfig实现注入

@Configuration
//@ComponentScan(basePackages = "com.shiftycat.soundsystem") //在Spring中启动组件扫描,默认扫描该类所在包及这个包下的所有子包
public class CDPlayerConfig {@Beanpublic CompactDisc nowAndThen() {return new nowAndThen();}// 方法一: 最简单的方法是引用创建bean的方法@Beanpublic CDPlayer cdPlayer() {return new CDPlayer(nowAndThen());}// 方法二: 请求一个CompactDisc作为参数,将CompactDisc注入到CDPlayer的构造器中,// 而且不用明确引用CompactDisc的@Bean方法。@Beanpublic CDPlayer cdPlayer(CompactDisc compactDisc) {return new CDPlayer(compactDisc);}// 方法三: 通过setter方法注入CompactDisc@Beanpublic CDPlayer cdPlayer(CompactDisc compactDisc) {CDPlayer  cdPlayer = new CDPlayer();cdPlayer.setCd(compactDisc);return cdPlayer;}
}

四、隐式的bean发现机制和自动装配

1. 自动化装配bean

​ Spring通过两个方面实现自动化装配:

  • 组件扫描(component scanning):Spring会自动发现应用上下文所创建的bean。
  • 自动装配(autowiring):Spring自动满足bean之间的依赖。

2. 步骤

1. 创建可被发现的bean

public interface CompactDisc {void play();
}public class nowAndThen implements CompactDisc{private String title = "Now And Then.";private String artist = "The Beatles";@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);}
}public interface MediaPlayer {void play();
}

2. 开启组件扫描

@Configuration
@ComponentScan(basePackages = "com.shiftycat.soundsystem") //在Spring中启动组件扫描,默认扫描该类所在包及这个包下的所有子包
public class CDPlayerConfig {}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd><context:component-scan base-package="com.shiftycat.soundsystem" />
</beans>
@Autowired
private CompactDisc compactDisc;@Test
public void compactDiscTest() {compactDisc.play();
}
Playing Now And Then. by The Beatles

3. 通过为bean添加注解实现自动装配

不管是构造器、Setter方法还是其他的方法,Spring都会尝试满足方法参数上所声明的依赖。假如有且只有一个bean匹配以来需求的话,那么这个bean将会被装配进来。
@Component
public class CDPlayer implements MediaPlayer{private CompactDisc cd;@Autowiredpublic CDPlayer(CompactDisc cd) {this.cd = cd;}@Autowiredpublic void setCd(CompactDisc cd) {this.cd = cd;}@Overridepublic void play() {System.out.println("Loading...");cd.play();}
}
@Autowired
private CDPlayer cdPlayer;
@Test
public void cdPlayerTest() {cdPlayer.play();
}
Loading...
Playing Now And Then. by The Beatles

五、导入和混合配置

1. 在JavaConfig中引用XML配置

​ 假如现存由两个config文件和一个XML文件,如何实现在一个JavaConfig文件中引用两个config文件并且在其中引入XML配置文件。

1. 配置文件1

public interface CompactDisc {void play();
}@Component
public class NowAndThen implements CompactDisc {private String title = "Now And Then.";private String artist = "The Beatles";@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);}
}@Configuration
public class CDConfig {@Beanpublic CompactDisc compactDisc() {return new NowAndThen();}
}

2. 配置文件2

public interface MediaPlayer {void play();
}@Component
public class CDPlayer implements MediaPlayer {private CompactDisc cd;public CDPlayer(CompactDisc cd) {this.cd = cd;}@Overridepublic void play() {System.out.println("Loading...");cd.play();}
}@Configuration
//@Import(CDConfig.class)
public class CDPlayerConfig {@Beanpublic CDPlayer cdPlayer(CompactDisc compactDisc) {return new CDPlayer(compactDisc);}
}

3. 配置文件3

public class BlackDisc implements CompactDisc {private String title;private String artist;private List<String> tracks;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getArtist() {return artist;}public void setArtist(String artist) {this.artist = artist;}public List<String> getTracks() {return tracks;}public void setTracks(List<String> tracks) {this.tracks = tracks;}@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);for (String track : tracks) {System.out.println("-Track: " + track);}}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:c="http://www.springframework.org/schema/c"xmlns:p="http://www.springframework.org/schema/p"xmlns:util="http://www.springframework.org/schema/util"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util.xsd"><bean id="blackDisc" class="com.shiftycat.importAndBlend.BlackDisc"p:artist="Now And Then."p:title="The Beatles"p:tracks-ref="tracks"></bean><util:list id="tracks"><value>I know it's true</value><value>It's all because of you</value><value>And if I make it through</value><value>It's all because of you</value><value>And now and then</value></util:list></beans>

4. 主要的Config文件

@Configuration
@Import({CDConfig.class, CDPlayerConfig.class})
@ImportResource("classpath:cd-config.xml")
public class SoundSystemConfig {}

5. 进行测试

@Test
public void JavaConfigTest() {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();context.register(SoundSystemConfig.class);context.refresh();System.out.println("BlackDisc: ");CompactDisc blackDisc = context.getBean(BlackDisc.class);blackDisc.play();System.out.println("\nnowAndThen: ");CompactDisc nowAndThen = context.getBean(NowAndThen.class);nowAndThen.play();System.out.println("\nCDPlayer: ");CDPlayer player = context.getBean(CDPlayer.class);player.play();
}

6. 测试结果

BlackDisc: 
Playing The Beatles by Now And Then.
-Track: I know it's true
-Track: It's all because of you
-Track: And if I make it through
-Track: It's all because of you
-Track: And now and thennowAndThen: 
Playing Now And Then. by The BeatlesCDPlayer: 
Loading...
Playing Now And Then. by The Beatles

2. 在XML配置中引用JavaConfig

​ 与在JavaConfig中引用XML配置一样,我们可以使用更高层次的配置文件,这个文件不声明任何的bean,只是负责将两个或更多的配置组合起来。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!--  用来导入JavaConfig类配置到Xml文件中  --><bean class="com.shiftycat.importAndBlend.CDConfig" /><!--  用来导入xml文件配置  --><import resource="cd-config.xml"/></beans>

《Spring实战(第4版)》

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/208243.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

代码随想录 62. 不同路径

题目 一个机器人位于一个 m x n 网格的左上角 &#xff08;起始点在下图中标记为 “Start” &#xff09;。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角&#xff08;在下图中标记为 “Finish” &#xff09;。 问总共有多少条不同的路径&#xff1f; 示例…

支付宝小程序接口传参会默认排序

一&#xff1a;问题 描述&#xff1a;最近项目中的接口都加了签名&#xff0c;在同步到支付宝小程序上时&#xff0c;发现有些接口报错&#xff0c;经过排查&#xff0c;导致报错的原因是因为传参顺序被支付宝小程序默认排序了&#xff0c;比如&#xff1a; 设置的原始参数&a…

当下流行视频剪辑软件会声会影2024,让你的视频制作更精彩

大家好呀&#xff01;今天小编给大家介绍一款超赞的视频编辑软件——会声会影2024&#xff01; 当下流行视频剪辑软件会声会影2024&#xff0c;让你的视频制作更精彩&#xff0c;会声会影2024不仅提供了各种酷炫的特效和滤镜&#xff0c;还有更多令人惊叹的功能等待着你的发掘…

【STM32】蓝牙氛围灯

Docs 一、项目搭建和开发流程 一、项目需求和产品定义 1.需求梳理和产品定义 一般由甲方公司提出&#xff0c;或由本公司市场部提出 需求的重点是&#xff1a;这个产品究竟应该做成什么样&#xff1f;有哪些功能&#xff1f;具体要求和参数怎样&#xff1f;此外还要考虑售价…

MongoDB SASL 鉴权方式 SCRAM-SHA-1步骤

转载于 MongoDB SCRAM-SHA-1 over SASL 文章目录 OverviewStep 1Step 2Step 3Edits I recently implemented SCRAM-SHA-1 over SASL for Fantom’s MongoDB driver so it could authenticate against MongoDB v3 databases. Much to my surprise, for such a massive breaking…

C++函数模板案例

利用函数模板封装一个排序的函数&#xff0c;可以对不同数据类型数组进行排序排序规则从大到小&#xff0c;排序算法为选择排序分别利用char数组和int数组进行测试 #include<iostream> using namespace std;template<class T> void myswap(T& a, T& b) {T…

[Python从零到壹] 七十三.图像识别及经典案例篇之图像去雾ACE算法和暗通道先验去雾算法实现

十月太忙&#xff0c;还是写一篇吧&#xff01;祝大家1024节日快乐O(∩_∩)O 欢迎大家来到“Python从零到壹”&#xff0c;在这里我将分享约200篇Python系列文章&#xff0c;带大家一起去学习和玩耍&#xff0c;看看Python这个有趣的世界。所有文章都将结合案例、代码和作者的经…

java中什么是守护线程?

在 Java 中&#xff0c;线程分为两种类型&#xff1a;用户线程&#xff08;User Thread&#xff09;和守护线程&#xff08;Daemon Thread&#xff09;。 用户线程&#xff08;User Thread&#xff09;&#xff1a; 用户线程是应用程序中的主要线程&#xff0c;当所有的用户线程…

实例分割网络:Mask RCNN

文章目录 网络结构Mask 分支RoIAlignRoIPooling的精度问题RoIAlign方法Mask RepresentationMask R-CNNNetwork Architecture实现细节实验结果与其他的实例分割网络的对比对比实验不同backbone的对比实验不同的激活函数的对比实验RoiAli

更多内窥镜维修技能学习与交流可关注西安彩虹

内窥镜结构及光学成像原理 众多品牌的硬镜其内部结构基本相似&#xff08;如下图&#xff09;&#xff0c;最关键的在于不同用途的硬镜在其结构上发生变化&#xff0c;包括光学成像系统和机械结构。光学成像系统由物镜系统、转像系统、目镜系统三大系统组成。 工作原理 被观察…

1文件+2个命令,无需安装,单机离线运行70亿大模型

1文件2个命令&#xff0c;无需安装&#xff0c;单机离线运行70亿大模型 大家好&#xff0c;我是老章 最近苹果发布了自己的深度学习框架--MLX&#xff0c;专门为自家M系列芯片优化。看了展示视频&#xff0c;这个框架还能直接运行Llama 7B的大模型&#xff0c;在M2 Ultral上运…

计算三位数每位上数字的和

分数 10 作者 python课程组 单位 福州大学至诚学院 补充程序实现计算&#xff1a; 输入一个三位的整数&#xff08;不接受实数&#xff09;&#xff0c;求这个三位数每一位上数字的和是多少&#xff1f;例如&#xff1a;输入&#xff1a;382&#xff0c;输出&#xff1a;和为…

用gdal正射校正遥感影像

目录 代码示例有相应的RPC文件用gdal命令行校正 使用 gdal.Warp函数可以非常方便对遥感影像进行正射校正&#xff0c;这个过程需要我们确定目标影像的几何信息&#xff0c;包括坐标系、分辨率以及需要配准到的区域或基准影像 代码示例 以下是一个使用gdal.Warp配准影像的基本…

MySQL中是如何insert数据的

正常insert数据&#xff0c;MySQL并不会显式加锁&#xff0c;而是通过聚簇索引的trx_id索引作为隐式锁来保护记录的。比如两个事务对一个非唯一的索引情况添加&#xff0c;会造成幻读 但在某些特殊情况下&#xff0c;隐式锁会转变为显式锁&#xff1a; 记录之间有间隙锁inser…

Channel Attention前言——一二阶统计量

统计量 简述 ​ 一阶统计量和二阶统计量是统计学中常用的两类统计量。一阶统计量是指只考虑随机变量本身的统计量&#xff0c;而二阶统计量则是指考虑随机变量之间关系的统计量。 一阶统计量 一阶统计量是指只考虑随机变量本身的统计量&#xff0c;通常包括以下几种&#x…

二叉树的非递归遍历(详解)

二叉树非递归遍历原理 使用先序遍历的方式完成该二叉树的非递归遍历 通过添加现有项目的方式将原来编写好的栈文件导入项目中 目前项目存在三个文件一个头文件&#xff0c;两个cpp文件&#xff1a; 项目头文件的代码截图&#xff1a;QueueStorage.h 项目头文件的代码&#xff…

达梦(主备)搭建

一、服务器配置 1.扩展基础盘 磁盘分区 /sbin/fdisk /dev/vda<<EOF &> /dev/null p n 4p w EOF 硬盘刷新 partx -s /dev/vda echo "Disk Partition /dev/vda4 Create OK!" pvcreate /dev/vda4 rootlvnamedf -h|grep "\-root"|awk {prin…

全电动注塑机市场分析:全球市场规模将达到223.23亿美元

注射成型机(简称注射机或注塑机)是将热塑性塑料或热固性料利用塑料成型模具制成各种形状的塑料制品的主要成型设备。 注射成型是通过注塑机和模具来实现的。 注塑机通常由注射系统、合模系统、液压传达动系统、电气控制系统、润滑系统、加热及冷却系统、安全监测系统等组成。 注…

如何运用gpt改写出高质量的文章 (1)

大家好&#xff0c;今天来聊聊如何运用gpt改写出高质量的文章 (1)&#xff0c;希望能给大家提供一点参考。 以下是针对论文重复率高的情况&#xff0c;提供一些修改建议和技巧&#xff1a; 如何运用GPT改写出高质量的文章 一、引言 随着人工智能技术的飞速发展&#xff0c;自然…

大一C语言作业 12.8

1.C 对一维数组初始化时&#xff0c;如果全部元素都赋了初值&#xff0c;可以省略数组长度。 这里没有指定数组长度&#xff0c;编译器会根据初始化列表的元素个数来确定数组长度。 2.C 在C语言中&#xff0c;字符数组是不能用赋值运算符直接赋值的。 3.C 在二维数组a中&#x…