一、bean

定义:被称作 bean 的对象是构成应用程序的支柱也是由 Spring IoC 容器管理的。bean 是一个被实例化,组装,并通过 Spring IoC 容器所管理的对象。

bean作用域
  • Singleton:是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,Singleton作用域是Spring中的缺省作用域。你可以在 bean 的配置文件中设置作用域的属性为 singleton,如下所示:
<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="singleton">
</bean>
  • Prototype:是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。
Bean的生命周期
  • Bean的生命周期可以表达为:Bean的定义——Bean的初始化——Bean的使用——Bean的销毁
public class Lion {public static void main(String[] args) {}private String name ;public Lion() {super();System.out.println( "public Lion()" );}public void init(){System.out.println( "public void init()" );}public void destory(){System.out.println( "public void destory()" );}}
XML配置文件中如下:<bean id="lion" class="vip.ycpower.ioc.lifecycle.Lion"p:name="辛巴"init-method="init"destroy-method="destory"scope="singleton"/>
bean的关系

-继承关系

  • 依赖关系
  • 引用关系
继承
<bean id="parent" class="vip.ycpower.ioc.relation.Foreigner"p:type="美国人"p:lastName="唐纳德"/><bean id="child" class="vip.ycpower.ioc.relation.Foreigner"p:firstName="特朗普"parent="parent"/>
依赖
public class Engine {public void init(){System.out.println( "[ Engine ] [ public void init() ]" );}public void start(){System.out.println( "[ Engine ] [ 引擎启动 ]" );}
}
public class Plane {private Engine engine;public void init(){System.out.println( "[ Plane ] [ public void init() ]" );}public void fly(){engine.start();System.out.println( "[ Plane ] [ 灰机起灰了 ]" );}
配置文件
<bean id="plane" class="vip.ycpower.ioc.relation.Plane" init-method="init" autowire="byName"depends-on="engine"/><bean id="engine" class="vip.ycpower.ioc.relation.Engine" init-method="init"/>
引用
<bean id="tz" class="java.util.TimeZone" factory-method="getDefault"/><bean id="timezoneUtil" class="vip.ycpower.ioc.relation.TimezoneUtil"><property name="timezoneId"><!-- 使用 idref 用于引用 一个 已经存在 的 bean 的 名称 --><idref bean="tz"/></property>

二、bean的实例化

1、 通过一个构造方法来实例化 Bean
public class Human {private Integer id ;private String name ;private char gender ;private Date birthdate ;private boolean married ;public Human() {super();System.out.println( "public Human()" );}public Human(Integer id, String name, char gender) {super();System.out.println( "public Human(Integer,String,char)" );this.id = id;this.name = name;this.gender = gender;}@Overridepublic String toString() {return "Human{" +"id=" + id +", name='" + name + '\'' +", gender=" + gender +", birthdate=" + birthdate +", married=" + married +'}';}
 <!--默认通过无参构造Date实例--><bean id="date" class="java.util.Date"/><!--默认通过无参构造Human实例--><bean id="firstHuman" class="vip.ycpower.ioc.injection.Human"><!--通过property为Human实例的各个属性赋值,通过setter注入--><property name="id" value="1001"/><property name="name" value="郭靖"/><property name="gender" value="男"/><property name="birthdate" ref="date"/><property name="married" value="true"/></bean><!--在bean标签内部通过使用constructor-arg 指定构造方法的参数,从而可以调用带有指定参数的构造方法--><bean id="secondHuman" class="vip.ycpower.ioc.injection.Human"><!-- constructor 构造方法 , arguments 参数 --><constructor-arg name="id" value="1002"/><constructor-arg name="name" value="黄蓉" /><constructor-arg name="gender" value="女"/></bean>
2、通过一个静态工厂方法来实例化 Bean
public class Sun {private static  final Sun SUN=new Sun();private Sun() {super();System.out.println(" public Sun()  ");}public static Sun getInstance() {System.out.println(" Sun.getInstance()");return SUN;}
}

xml配置文件

 <!-- *** 静态工厂方法 ( static factory method ) *** --><!-- 通过 Sun 类的 getInstance() 方法来返回 Sun 实例 --><bean id="sun" class="vip.ycpower.ioc.beancreation.Sun" factory-method="getInstance"/><!-- 通过调用  Calendar 类的 getInstance() 方法返回 Calendar 实例 -->
<bean id="calendar" class="java.util.Calendar" factory-method="getInstance"/>
3、 使用一个实例工厂方法来实例化 Bean
public class CarFactory {public CarFactory(){super();System.out.println(" CarFactory :  public CarFactory()");}private final String[] brands={ "秦" , "汉" , "唐" , "宋" ,  "元" , "明" };private final Random rand=new Random();public Car produce(){Car c=new Car();int index=rand.nextInt(brands.length);String b=brands[index];c.setBrand(b);return c;}}
 <!--声明一个CarFactory类型的bean--><bean id="carFactory" class="vip.ycpower.ioc.beancreation.CarFactory"/><!--通过CarFactory的produce()方法创建一个Car类型的bean--><bean id="car" factory-bean="carFactory" factory-method="produce"/>
4、 通过FactoryBean实现自定义实例化逻辑
public class Bus {private String brand;public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;System.out.println("[ Bus ] - [ public void setBrand(String) ]");}
}public class BusFactoryBean implements FactoryBean<Bus> {private String name;@Overridepublic Bus getObject() throws Exception {System.out.println( "[ BusFactoryBean ] - [ public Bus getObject() throws Exception ]" );Bus bus=new Bus();bus.setBrand(name);return bus;}@Overridepublic Class<?> getObjectType() {// getObject 方法返回的是什么类型,这里就返回那个类型对应的 Class 对象return Bus.class ;}

XML配置文件

<!--凡是在bean标签中的class指定的是实现过FactoryBean的类将来创建的这个bean实例一定是FactoryBean这个实现类的getObject()方法返回的类型Bus的对象bus而不是实现类BusFactoryBean的对象--><bean id="bus" class="vip.ycpower.ioc.beancreation.BusFactoryBean"><property name="name" value="奔驰"/></bean><!----><bean id="date" class="vip.ycpower.ioc.beancreation.DateFactoryBean"><property name="year" value="1993"/><property name="month" value="9"/><property name="date" value="23"/><property name="hours" value="9"/><property name="minutes"  value="20"/><property name="seconds" value="34"/></bean>
</beans>

三、依赖注入

Spring 容器使用依赖注入(DI)来管理组成一个应用程序的组件。这些对象被称为 Spring Beans

1、属性注入方式
  • setter方法注入
  • 构造方法注入
  • 集合属性注入
    • list属性注入
    • set属性注入
    • map属性注入
    • properties属性注入
  • 命名空间 p:c: 的使用
(1) setter方法注入
<bean id="heihuang" class="vip.ycpower.ioc.injection.Sinaean"><property name="id" value="1002"/><property name="name" value="黑黄"/><property name="gender" value="男"/><property name="married" value="false"/><property name="birthdate"><!-- 使用 DateFactoryBean 来创建任意年月日对应的 Date 对象--><bean class="vip.ycpower.ioc.beancreation.DateFactoryBean"><property name="year" value="1780"/><property name="month" value="3"/><property name="date" value="1"/></bean></property></bean>说明:在这里birthdate 字段值的bean写在heihuang  bean的外面,然后用ref引用birthdate的bean的id值,实现bean之间的注入即<bean id="date" class="vip.ycpower.ioc.beancreation.DateFactoryBean"><property name="year" value="12"/><property name="month" value="2"/><property name="date" value="30"/>
</bean>
<bean id="heihuang" class="vip.ycpower.ioc.injection.Sinaean">
<property name="birthdate" ref="date"/></bean>
( 2) 构造方法注入
  • 按构造方法参数索引和类型匹配注入
  • 按参数索引匹配注入
  • 按参数类型匹配注入
 <!--public Sinaean(Integer id, String name, char gender) --><bean id="fourth" class="vip.ycpower.ioc.injection.Sinaean"><constructor-arg index="0" type="java.lang.Integer" value="1003"/><constructor-arg index="1" type="java.lang.String" value="紫霞仙子"/><constructor-arg index="2" type="char" value="女"/></bean>说明:此处构造函数参数与bean注入的属性顺序、个数一致
<constructor-arg index="1"  value="紫霞仙子"/> 索引<constructor-arg type="java.lang.String" value="紫霞仙子"/> 参数类信息
(3) 集合属性注入
public class Student {private Integer id ;private String name ;private Set<String> hobbies;private List<Date> luckDay;private Map<String,String> contacts; 表示联系人列表private Properties address ;//联系人地址set/get方法省略}
3.1 set方法注入
 <bean id="first" class="vip.ycpower.ioc.collection.Student"><property name="id" value="1001"/><property name="name" value="重阳真人"/><property name="hobbies"><set><value>抄经</value><value>炼丹</value><value>云游四海</value><ref bean="string"/>   //注入id为string的bean<bean class="java.lang.String"><constructor-arg type="java.lang.String" value="惩恶除害"/></bean></set></property></bean>
3.2 list方法注入
</bean><bean id="second" class="vip.ycpower.ioc.collection.Student" p:id="2002" p:name="无始大帝"><property name="luckDay"><list><ref bean="date"/><bean class="vip.ycpower.ioc.beancreation.DateFactoryBean"><property name="year" value="2018"/><property name="month" value="12"/><property name="date" value="12"/></bean></list></property></bean>
p:id="2002" 这里用到了p标签
3.3 map方法注入
<bean id="third" class="vip.ycpower.ioc.collection.Student" p:id="3003" p:name="狠人大帝"><property name="contacts"><map><entry key="紫阳真人" value="紫阳山紫阳洞"/><entry key="东华帝君" value="东华仙山"/><entry><key><value>北极大帝</value></key><value>天之北北极宫</value></entry></map></property></bean>
3.4 properties 方法注入
<bean id="fourth" class="vip.ycpower.ioc.collection.Student" p:id="4001" p:name="绝代神王"><property name="address"><props><prop key="仙府">苍穹天宫</prop><prop key="师承">狠人大帝</prop></props></property></bean>
(4) 命名空间 p:c: 以及util 的注入

在xml命名空间加入如下

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:util="http://www.springframework.org/schema/util"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"><util:properties id="properties"><prop key="仙府">苍穹天宫</prop><prop key="师承">狠人大帝</prop></util:properties><bean id="student" class="vip.ycpower.ioc.collection.Student"p:id="5006"p:name="南极仙翁"p:hobbies-ref="set"p:luckDay-ref="list"p:contacts-ref="map"p:address-ref="properties"/>
(5) SpEl、

支持属性调用及方法调用,完成 bean 之间的注入

四、bean的自动装配(autowire)

  • Beans 自动装配
    我们可以使用元素来声明 bean 和通过使用 XML 配置文件中的和元素来注入 。
    Spring 容器可以在不使用和 元素的情况下自动装配相互协作的 bean 之间的关系,这有助于减少编写一个大的基于 Spring 的应用程序的 XML 配置的数量。

  • 自动装配模式
    下列自动装配模式,它们可用于指示 Spring 容器为来使用自动装配进行依赖注入。你可以使用元素的 autowire 属性为一个 bean 定义指定自动装配模式。

1、constructor

2、byName:会自动装配对象中属性与Bean id相同的Bean

3、byType

1、constructor

//Citizen
public class Citizen {private Integer id ;private String name ;// 维护从 Citizen 到 IdentityCard 的 一对一 关联关系private IdentityCard card ; // 当前公民的身份证public Citizen() {super();}public Citizen( IdentityCard card ) {super();System.out.println( "public Citizen(IdentityCard)" );System.out.println( "【 " + card + " 】");this.card = card;}
// IdentityCard 类public class IdentityCard {private Integer id ;private String cardNo ; // 身份证编号public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getCardNo() {return cardNo;}public void setCardNo(String cardNo) {this.cardNo = cardNo;}}
<bean id="identityCard" class="vip.ycpower.ioc.autowire.IdentityCard"p:id="6122"p:cardNo="6123441223111132"/><bean id="citizen" class="vip.ycpower.ioc.autowire.Citizen"p:id="1001"p:name="比尔盖茨"autowire="constructor"/>

说明:类似于 byType,但该类型适用于构造函数参数类型。即在创建citizen时会去寻找bean id与所在类中的构造函数参数一致的 bean

2、byName

<bean id="identityCard" class="vip.ycpower.ioc.autowire.IdentityCard"p:id="6122"p:cardNo="6123441223111132"/><bean id="citizen" class="vip.ycpower.ioc.autowire.Citizen"p:id="1001"p:name="比尔盖茨"autowire="byName"/>

说明:在创建citizen的bean时会通过byName寻找与Citizen这个类的identityCard属性的名称一致的bean,然后注入到这个bean中

3、byType

<bean id="identityCard" class="vip.ycpower.ioc.autowire.IdentityCard"p:id="6122"p:cardNo="6123441223111132"/><bean id="citizen" class="vip.ycpower.ioc.autowire.Citizen"p:id="1001"p:name="比尔盖茨"autowire="byType"/>

说明:在创建citizen的bean时会通过byType寻找与Citizen这个类中identityCard属性的类型名称一致的bean,然后注入到这个bean中;byType在匹配类型时忽略bean id的大小写。

  • 以上使用autowire属性,直接省略了p:identityCard-ref="identityCard"这个属性的注入

本文参考:https://www.w3cschool.cn/wkspring/nukv1ice.html

Spring的bean的注创建、依赖注入、自动装配相关推荐

  1. spring学习(10):创建项目(自动装配)

    首先创建项目 pom.xml的配置文件 <?xml version="1.0" encoding="UTF-8"?> <project xml ...

  2. 2.4 Spring Framework 5.x之DI(依赖注入)

    依赖注入(DI) 依赖注入(DI)是一个过程,通过这个过程,对象只能通过构造函数参数,工厂方法的参数或在构造对象实例后在对象实例上设置的属性来定义它们的依赖关系(即,它们使用的其他对象).从工厂方法返 ...

  3. 【转载】详解 Spring 3.0 基于 Annotation 的依赖注入实现

    转载自:http://www.ibm.com/developerworks/cn/opensource/os-cn-spring-iocannt/ Spring 的依赖配置方式与 Spring 框架的 ...

  4. 详解 Spring 3.0 基于 Annotation 的依赖注入实现--转载

    使用 @Repository.@Service.@Controller 和 @Component 将类标识为 Bean Spring 自 2.0 版本开始,陆续引入了一些注解用于简化 Spring 的 ...

  5. Spring容器,控制反转,依赖注入

    Spring boot学习之旅,为更好督促自己学习以记之,仅供参考. spring容器 程序启动的时候会创建spring容器,扫描给spring容器一个清单,比如:@Controller, @Bean ...

  6. SSM—Spring框架,IOC理论推导,Hello Spring,IOC创建对象方式,Spring的配置,DI(依赖注入)

    文章目录 1.Spring 1.1.Spring简介(了解) 1.2.spring优点 1.3.组成(七大模块) 1.4.拓展 2.IOC理论推导 2.1.IOC本质 3.Hello Spring 4 ...

  7. spring中的控制反转和依赖注入之间的关系

    Spring中的控制反转:把new这一个过程交给了spring容器去处理. 控制反转就是将new对象这一个过程交给外部去做(即Spring)而不是自己去创建. 图中的1"控制正转" ...

  8. 使用Spring.Net对Web页面进行依赖注入

    今天看到这篇文章 Unity&WebForm(1): 自定义IHttpHandlerFactory使用Unity对ASP.NET Webform页面进行依赖注入,这是一个很好的思路,自定义IH ...

  9. spring系列-注解驱动原理及源码-自动装配

    目录 一.spring规范的bean自动注入 1.使用@Autowired自动注入 2.使用@Qualifier指定需要装配的组件 3.使用@Autowired装配null对象 4.使用@Primar ...

最新文章

  1. zabbix的主动模式和被动模式、添加监控主机、添加自定义模板、处理图形中的乱码、自动发现...
  2. 编码最佳实践——Liskov替换原则
  3. hbase查询语句_Sqoop实操|Sqoop导入Parquet文件Hive查询为null问题
  4. 牛客题霸 NC16 判断二叉树是否对称
  5. 2006年4月全国计算机等级考试二级Java语言程序设计
  6. 如何使用ABP进行软件开发之基础概览
  7. 多媒体视频知识入门贴zt(一)
  8. FileOutputStream为false时候注意的问题
  9. 红橙Darren视频笔记 AOP简介
  10. error installing service: 拒绝访问。 (5)_CentOS7x86_64安装Tomcat8.5手册
  11. Android 编程下的计时器
  12. 如何用OBS录制Mac系统声音
  13. php渐变闪动字体代码,33种超好看彩色闪字渐变代码分享
  14. azure 云上安装部署nginx
  15. ArcGIS山体坡度、坡向分析
  16. 2000亿元贴息贷款,医疗系统上云,解锁医护协同新玩法
  17. readmemh函数引用的txt格式_memory - 在Verilog中,我尝试使用$ readmemb来读取.txt文件,但它仅在内存中加载xxxxx(不必担心) - 堆栈内存溢出...
  18. android adb 屏幕分辨率,利用 adb 来修改 Android 安卓的分辨率(另类安卓省电方法)...
  19. 影视小程序完美版源码
  20. 输入某年某月某日,判断这一天是这一年的第几天?考虑闰年的情况

热门文章

  1. Python Text Processing with NLTK 2.0 Cookbook代码笔记
  2. Excel中随机生成数字,函数RANDBETWEEN()的使用
  3. 使用商业智能BI工具有哪些好处?
  4. [学习笔记]UnityShader入门精要_第12章_屏幕后处理效果
  5. 冒泡排序c语言子程序,C语言之冒泡排序算法
  6. linux tar zcxf,tar/gzip/zip文件打包、压缩命令
  7. vim末行模式下的替换操作
  8. 测试之全流程质量保证
  9. Cubase中文版教程分享:如何通过音频剪辑软件创建工程
  10. 三色球问题python_面试题-三色球问题