美文网首页
spring对象创建特性

spring对象创建特性

作者: simplerandom | 来源:发表于2020-07-23 14:25 被阅读0次

对象创建时机

<!--单例加载xml时创建,多例调用getbean时创建-->
    <bean scope="singleton" id="hello" class="org.spring.HelloFactory" factory-method="getHello"></bean>
    <bean scope="prototype" id="hello" class="org.spring.HelloFactory" factory-method="getHello"></bean>

单例生命周期

<bean init-method="init" destroy-method="des" scope="singleton" id="hello" class="org.spring.HelloFactory" factory-method="getHello"></bean>

容器销毁触发des方法
((ClassPathXmlApplicationContext) context).close();

多例生命周期

对象消亡利用java垃圾回收

di依赖注入

构造函数注入

基本类型直接注入
对象类型先由容器创建对象后ref引用

<bean init-method="init" destroy-method="des" scope="singleton" id="hello" class="org.spring.Hello">
        <constructor-arg name="age" value="24"></constructor-arg>
        <constructor-arg name="date" ref="now"></constructor-arg>
    </bean>
    <bean id="now" class="java.util.Date"></bean>

必须重写构造方法

set方法注入

<bean init-method="init" destroy-method="des" scope="singleton" id="hello" class="org.spring.Hello">
        <property name="age" value="25"></property>
    </bean>

调用默认构造方法生成对象后调用set方法赋值

给复杂类型赋值

<bean init-method="init" destroy-method="des" scope="singleton" id="hello" class="org.spring.Hello">
        <property name="arr">
            <array>
                <value>1</value>
                <value>50</value>
            </array>
        </property>
    </bean>

相关文章

网友评论

      本文标题:spring对象创建特性

      本文链接:https://www.haomeiwen.com/subject/szqhlktx.html