spring 自动装配 bean 有哪些方式?

spring 配置文件中 <bean> 节点的 autowire 参数可以控制 bean 自动装配的方式

  • default - 默认的方式和 "no" 方式一样
  • no - 不自动装配,需要使用 <ref />节点或参数
  • byName - 根据名称进行装配
  • byType - 根据类型进行装配
  • constructor - 根据构造函数进行装配

文档解释

Attribute : autowire
Controls whether bean properties are "autowired". This is an automagical process in which bean references don't need to be coded explicitly in the XML bean definition file, but rather the Spring container works out dependencies. The effective default is "no". There are 4 modes: 1. "no" The traditional Spring default. No automagical wiring. Bean references must be defined in the XML file via the <ref/> element (or "ref" attribute). We recommend this in most cases as it makes documentation more explicit. Note that this default mode also allows for annotation-driven autowiring, if activated. "no" refers to externally driven autowiring only, not affecting any autowiring demands that the bean class itself expresses. 2. "byName" Autowiring by property name. If a bean of class Cat exposes a "dog" property, Spring will try to set this to the value of the bean "dog" in the current container. If there is no matching bean by name, nothing special happens. 3. "byType" Autowiring if there is exactly one bean of the property type in the container. If there is more than one, a fatal error is raised, and you cannot use byType autowiring for that bean. If there is none, nothing special happens. 4. "constructor" Analogous to "byType" for constructor arguments. If there is not exactly one bean of the constructor argument type in the bean factory, a fatal error is raised. Note that explicit dependencies, i.e. "property" and "constructor-arg" elements, always override autowiring. Note: This attribute will not be inherited by child bean definitions. Hence, it needs to be specified per concrete bean definition. It can be shared through the 'default-autowire' attribute at the 'beans' level and potentially inherited from outer 'beans' defaults in case of nested 'beans' sections (e.g. with different profiles).Data Type : string
Default Value : default
Enumerated Values : - default- no- byName- byType- constructor

代码示例

1、no 方式

spring 配置文件,使用 ref 参数注入 bean,必须要有对象的 setter 方法,这里即 Person 的 setFr 方法。

没有 <property name="fr" ref="fr"></property> 因没有注入 fr 属性,会报空指针错误。

<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><bean id="person" class="constxiong.interview.assemble.Person" autowire="no"><property name="fr" ref="fr"></property></bean><bean id="fr" class="constxiong.interview.assemble.FishingRod"></bean></beans>

鱼竿 bean

package constxiong.interview.assemble;/*** 鱼竿* @author ConstXiong* @date 2019-07-17 09:53:15*/
public class FishingRod {/*** 被使用*/public void used() {System.out.println("钓鱼...");}
}

人 bean

package constxiong.interview.assemble;/*** 人* @author ConstXiong* @date 2019-07-17 09:54:56*/
public class Person {private FishingRod fr;/*** 钓鱼*/public void fish() {fr.used();}public void setFr(FishingRod fr) {this.fr = fr;}}

测试代码

package constxiong.interview.assemble;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class AssembleTest {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("spring_assemble.xml");Person person = (Person)context.getBean("person");person.fish();}}

2、byName 也是需要相应的 setter 方法才能注入

修改 spring 配置文件 autowire="byName"

<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><bean id="person" class="constxiong.interview.assemble.Person" autowire="byName"></bean><bean id="fr" class="constxiong.interview.assemble.FishingRod"></bean></beans>

其他不变

3、byType 也是需要相应的 setter 方法才能注入

修改 spring 配置文件 autowire="byType"

<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><bean id="person" class="constxiong.interview.assemble.Person" autowire="byType"></bean><bean id="fr" class="constxiong.interview.assemble.FishingRod"></bean></beans>

其他不变

4、constructor 无需 setter 方法,需要通过 构造方法注入 bean

修改 spring 配置文件autowire="byType"

Person 类去除 setFr 方法,添加构造方法设置 fr 属性

<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><bean id="person" class="constxiong.interview.assemble.Person" autowire="constructor"></bean><bean id="fr" class="constxiong.interview.assemble.FishingRod"></bean></beans>
package constxiong.interview.assemble;/*** 人* @author ConstXiong* @date 2019-07-17 09:54:56*/
public class Person {private FishingRod fr;public Person(FishingRod fr) {this.fr = fr;}/*** 钓鱼*/public void fish() {fr.used();}}

1、2、3、4 的测试结果一致,打印

钓鱼...

  • Java 自学指南
  • Java 面试题汇总PC端浏览【点这里】
  • Java 面试题汇总小程序浏览,扫二维码


【Java面试题与答案】整理推荐

  • 基础与语法
  • 集合
  • 网络编程
  • 并发编程
  • Web
  • 安全
  • 设计模式
  • 框架
  • 算法与数据结构
  • 异常
  • 文件解析与生成
  • Linux
  • MySQL
  • Oracle
  • Redis
  • Dubbo

spring 自动装配 bean 有哪些方式?相关推荐

  1. spring自动装配Bean的五种方式

    no:默认方式,手动装配方式,需要通过ref设定bean的依赖关系 byName:根据bean的名字进行装配,当一个bean的名称和其他bean的属性一致,则自动装配 byType:根据bean的类型 ...

  2. Spring自动装配Bean

    除了使用 XML 和 Annotation 的方式装配 Bean 以外,还有一种常用的装配方式--自动装配.自动装配就是指 Spring 容器可以自动装配(autowire)相互协作的 Bean 之间 ...

  3. spring(2)装配Bean

    [0]README 0)本文部分文字描述转自:"Spring In Action(中/英文版)",旨在review  spring(2)装配Bean 的相关知识: 1)在sprin ...

  4. spring注解驱动开发-4 Spring 自动装配

    Spring 自动装配 前言 Spring 自动装配的几种方式 1.@Autowired @Qualifier("组件id") @Primary 2.@Resource方式 3.@ ...

  5. (Spring)自动装配bean

    文章目录 自动装配bean 1. 环境搭建 2. byName自动装配 3. byType自动装配 4. 使用注解自动装配 4.1 @Autowired和@Qualifier 4.2 @Resourc ...

  6. Spring实战(三)Spring中装配Bean的三种方式---XML、JavaConfig、AutoWire

    创建应用对象之间协作关系的行为称为装配(wiring),这也是依赖注入的本质. Spring容器负责创建应用程序中的bean并通过DI来协调这些对象之间的关系,而开发者需要告诉Spring需要创建哪些 ...

  7. 学习篇(一)- Spring自动装配的方式

    Spring自动装配的方式 1. 什么是自动装配? ​ 自动装配就是会通过Spring 的上下文为你找出相应依赖项的类,通俗的说就是Spring 会在上下文中自动查找,并自动给Bean装配与其相关的属 ...

  8. Spring自动装配的方式

    Spring自动装配的方式 Spring 装配包括手动装配和自动装配,手动装配是有基于xml 装配.构造方法.setter 方法等 自动装配有五种自动装配的方式,可以用来指导Spring 容器用自动装 ...

  9. spring二:装配bean(自动装配)

    创建应用对象之间协作关系的行为通常称为装配(wiring),这就是依赖注入(DI)的本质. Spring提供了三种主要的装配机制: 1. 在xml中进行显式配置.  2. 在java中进行显式配置. ...

  10. Spring学习笔记--自动装配Bean属性

    Spring提供了四种类型的自动装配策略: byName – 把与Bean的属性具有相同名字(或者ID)的其他Bean自动装配到Bean的对应属性中. byType – 把与Bean的属性具有相同类型 ...

最新文章

  1. swift写的摇骰子程序,开源了
  2. android 设置窗口透明效果,android - 如何将对话框窗口背景设置为透明,而不影响其边距...
  3. mongoTemplate使用总结
  4. Mongodb参数详解(参考:http://blog.csdn.net/freebird_lb/article/details/8229567)
  5. 史上最怂黑客?新病毒从上线到“自首”只勒索到五块钱,最后主动提交了密钥...
  6. mysql 特殊字符支持_mysql 解决生僻字,特殊字符插入失败
  7. CRM WebClient UI Relationship drop down list render logic
  8. dotnet 从零开始写一个人工智能 网络模型
  9. 前端学习(1854)vue之电商管理系统电商系统之安装mysql
  10. TypeError: can't pickle _thread.RLock objects
  11. 大数据下单集群如何做到2万+规模?
  12. day9 java的实例语句块和代码执行顺序
  13. 图像处理(1)----图像压缩
  14. 315页 A Tutorial on Graph Neural Networks for NLP
  15. 苹果Mac重复文件清理工具:​​​​Tidy Up
  16. 模式识别人工神经网络BP算法
  17. Matlab绘制折线图及局部放大图
  18. S3C2410 通用异步收发UART 串口通信
  19. matlab如何根据历年gdp找增长规律,人均gdp增长率_中国历年gdp数据图解 中国历年gdp增长率及人均GDP 1978年 2016年...
  20. 程序员公众号编辑工具

热门文章

  1. 最大子序列、最长连续公共子串(连续)、最长公共子序列(动态规划)
  2. android 8.0 图标规范,Android 8.0自适应图标
  3. .NET 6 中的 Http Logging 中间件
  4. 相机镜头等效焦距和实际焦距换算
  5. 英雄联盟显示计算机内存不足怎么办,玩英雄联盟内存不足的解决方法
  6. windows10安装虚拟机virtualbox详细步骤
  7. Metrics、Tracing、Logging的融合
  8. 视频渲染靠cpu还是显卡 视频渲染的作用是什么
  9. Angular 依赖注入框架里 useExisting 和 useClass 的使用场景
  10. 我爱淘冲刺阶段站立会议2每天任务4