不同数据类型的依赖注入(二):Inner beans & Collections & 注入null或空字符串

不同数据类型的依赖注入(二):Inner beans & Collections & 注入null或空字符串

内部bean(Inner Beans)

即在,<property/><constructor-arg/>标签中,定义子标签<bean/>。举例:

<bean id="outer" class="...">
    <!-- instead of using a reference to a target bean, simply define the target bean inline -->
    <property name="target">
        <bean class="com.example.Person"> <!-- this is the inner bean -->
            <property name="name" value="Fiona Apple"/>
            <property name="age" value="25"/>
        </bean>
    </property>
</bean>

用于“封装式”的注入,与使用ref引用的方式注入不同,内部bean是直接定义在内部,不需要指定id/name和scope属性(即使指定了这些属性,容器也会无视)

内部bean不能被独立的访问,也不能被注入到其他的bean中(因为没有name,所以不能引用),这个匿名的内部bean体现了一定的封装性。

内部bean的实例化依赖于外部bean的实例化,当外部bean实例化时,内部bean才会实例化

集合类型的注入(Collections)

对于集合类型的bean,例如List、Set、Map以及Properties,依赖注入时,可以使用<list/><set/><map/><props/>。举一个例子,包含了上述集合类型:

<bean id="moreComplexObject" class="example.ComplexObject">
    <!-- results in a setAdminEmails(java.util.Properties) call -->
    <property name="adminEmails">
        <props>
            <prop key="administrator">[email protected]</prop>
            <prop key="support">[email protected]</prop>
            <prop key="development">[email protected]</prop>
        </props>
    </property>
    <!-- results in a setSomeList(java.util.List) call -->
    <property name="someList">
        <list>
            <value>a list element followed by a reference</value>
            <ref bean="myDataSource" />
        </list>
    </property>
    <!-- results in a setSomeMap(java.util.Map) call -->
    <property name="someMap">
        <map>
            <entry key="an entry" value="just some string"/>
            <entry key ="a ref" value-ref="myDataSource"/>
        </map>
    </property>
    <!-- results in a setSomeSet(java.util.Set) call -->
    <property name="someSet">
        <set>
            <value>just some string</value>
            <ref bean="myDataSource" />
        </set>
    </property>
</bean>      

注入null

<bean class="ExampleBean">
    <property name="email">
        <null/>
    </property>
</bean>

等价于:

exampleBean.setEmail(null);

注入空字符串

<bean class="ExampleBean">
    <property name="email" value=""/>
</bean>

等价于:

exampleBean.setEmail("");
发布了213 篇原创文章 · 获赞 116 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq2071114140/article/details/104212699