叩丁狼java学习第十四天-SpringBean和依赖注入

发布于 2021-03-25  1259 次阅读


注意:factoryBean工厂创建的bean在未注入的状态下,尽管配置了单例也不会在容器创建时初始化。

1.bean 作用域

singleton:单例 ,在 Spring IoC 容器中仅存在一个 bean 实例 (缺省默认的 scope)。
prototype:多例 ,每次从容器中调用 Bean 时,都返回一个新的实例,即每次调用 getBean() 时
,相当于执行 new XxxBean():不会在容器启动时创建对象。
request:用于 web 开发,将 Bean 放入 request 范围,request.setAttribute("xxx") , 在同一个request 获得同一个 Bean。
session:用于 web 开发,将 Bean 放入 Session 范围,在同一个 Session 获得同一个 Bean。
application:Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext。
websocket:Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext。

2.bean 初始化和销毁

<bean id="myDataSource" class="cn.wolfcode._02_ioc.MyDataSource"
init-method="init" destroy-method="close" scope="prototype"/>

3.DI 概述

指 Spring 创建对象的过程中,将对象依赖属性通过配置设值给该对象。

4.注入常量值

<bean id="employee" class="cn.wolfcode._03_di.Employee">
<!-- name 写属性名 value 是写属性值 -->
   <property name="name" value="罗老师"/>
   <property name="age" value="12"/>
   <property name="salary" value="1000000"></property>
</bean>

5.注入 bean

    <bean id="son" class="init.Son" >
        <property name="name" value="貌似"/>
    </bean>

    <bean id="father" class="init.Father">
        <property name="son" ref="son" />
    </bean>

欢迎欢迎~热烈欢迎~