IOC系列【XML装配Bean】:XML中属性注入


属性注入是通过bean标签中的property标签来实现的。

1. Bean注入

  通过property标签中的ref属性来实现。

1.1 Bean定义

@Data
public class User {
	// 该属性是一个Class
    private Cat cat;
}

@Data
public class Cat {
    private String name;
    private String color;
}

1.2 Bean注入

<bean class="com.learning.spring.ioc.User" id="user">
    <!--通过ref属性来注入关联的Bean-->
    <property name="cat" ref="cat"/>
</bean>
<bean class="com.learning.spring.ioc.Cat" id="cat">
    <property name="name" value="小白"/>
    <property name="color" value="白色"/>
</bean>

2. 数组注入

2.1 Bean定义

@Data
public class User {
    private Cat[] cats;
    private String[] books;
}

2.2 数组注入

<bean class="com.learning.spring.ioc.Cat" id="cat1">
    <property name="name" value="小白"/>
    <property name="color" value="白色"/>
</bean>
<bean class="com.learning.spring.ioc.Cat" id="cat2">
    <property name="name" value="小黑"/>
    <property name="color" value="黑色"/>
</bean>

<bean class="com.learning.spring.ioc.User" id="user">
    <!--通过ref-->
    <property name="cats">
        <array>
            <ref bean="cat1"/>
            <ref bean="cat2"/>
        </array>
    </property>
    <property name="books">
        <array>
            <value>水浒传</value>
            <value>西游记</value>
        </array>
    </property>
</bean>

3. Map注入

3.1 Bean定义

@Data
public class User {
    private Map<String, String> books;
}

3.2 Map注入

<bean class="com.learning.spring.ioc.User" id="user">
    <property name="books">
        <map>
            <entry key="name" value="小花"/>
            <entry key="age" value=" 23"/>
        </map>
    </property>
</bean>

4. List注入

4.1 Bean定义

@Data
public class User {
    private List<String> bookNames;
}

4.2 List注入

<bean class="com.learning.spring.ioc.User" id="user">
    <property name="bookNames">
        <list>
            <value type="java.lang.String">小花</value>
            <value type="java.lang.String">小树</value>
        </list>
    </property>
</bean>

5. Set注入

5.1 Bean定义

@Data
public class User {
    private Set<String> bookNames;
}

5.2 Set注入

<bean class="com.learning.spring.ioc.User" id="user">
    <property name="bookNames">
        <set>
            <value type="java.lang.String">小花</value>
            <value type="java.lang.String">小树</value>
        </set>
    </property>
</bean>

6. Properties注入

6.1 Bean定义

@Data
public class User {
    private Properties info;
}

6.2 Properties注入

<bean class="com.learning.spring.ioc.User" id="user">
       <property name="info">
           <props>
               <prop key="name">admin</prop>
               <prop key="age">23</prop>
           </props>
       </property>
</bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值