Spring Beans.xml多种注入

多种类型的注入方式

对象的属性

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      https://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="Address" class="com.liu.pojo.Address">
<property name="address" value="11.com"></property>
    </bean>
    <bean id="StName" class="com.liu.pojo.Student">

        <!--第一种,普通注入,value-->
        <property name="name" value="小明"></property>

        <!--第二种,bean引用注入,ref-->
        <property name="address" ref="Address"></property>

        <!--第三种,数组注入-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>三国</value>
                <value>水浒</value>
                <value>西游</value>
            </array>
        </property>

        <!--第四列表注入-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>打球</value>
                <value>看电影</value>
            </list>
        </property>
        <!--第五Map注入  entry-->
        <property name="card">
            <map>
                <entry key="身份证" value="11111"></entry>
                <entry key="银行卡" value="22222"></entry>
            </map>
        </property>

        <!--第六种Set注入-->
        <property name="games">
            <set>
                <value>lol</value>
                <value>QQ</value>
                <value>war3</value>
            </set>
        </property>

        <!--第七种,null注入-->
        <property name="wife">
            <null></null>
        </property>

        <!--第八种,Properties注入-->
        <property name="info">
        <props>
            <prop key="学号">PC9527</prop>
            <prop key="寝室">C栋301</prop>
        </props>
        </property>
    </bean>

</beans>

test

import com.liu.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext Context = new ClassPathXmlApplicationContext("beans.xml");
        Student stName = (Student) Context.getBean("StName");
        System.out.println(stName.toString());

    }
}
posted @   小幼虫虫  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示