Spring IOC - XML

本文详细介绍了如何在Spring框架中使用IoC容器进行类的管理,包括bean标签的配置、不同方式获取bean对象以及依赖注入的使用。通过实例展示了如何通过id、类名、接口等方式获取对象并调用方法。

           1)作用:将自己的类交给IOC容器来负责,当需要每个类的对象时,不需要再通过

                             new 的关键字来造对象,直接从IOC容器中获取即可。

        2)用法:

                1》:通过bean标签来进行类的管理

                        bean标签的常用属性:

                                id:唯一标识

                                class:用于指明要管理的类(全类名)

                                scope:表示是单例模式(共用一个对象) 还是 多例模式(多个对象)

<bean id="helloworld" class="cn.wkl.spring.pojo.HelloWorld"></bean>

                2》:bean 标签中可以嵌套 property 标签,用来表示对象的属性(有set方法)

                                name:就是属性名

                                value:就是属性值

    <bean id="studentTwo" class="cn.wkl.spring.pojo.Student">
        <!--依赖注入:为类型的属性赋值-->
        <property name="age" value="18"></property>
        <property name="gender" value="男"></property>
        <property name="sid">
            <null/> <!--将sid的值赋值为空指针-->
        </property>
        <property name="sname" value="独酌"></property>
    </bean>

                3》:bean对象的类类型的赋值

<bean id="studentThree" class="cn.wkl.spring.pojo.Student">
        <property name="sname" value="张三"></property>
        <property name="sid" value="01"></property>
        <property name="gender" value="男"></property>
        <property name="age" value="18"></property>
        <!--为属性的实体类赋值 ref:引用某个bean的id-->
        <property name="clazz" ref="clazzOne"></property>
    </bean>

    <bean id="clazzOne" class="cn.wkl.spring.pojo.Clazz">
        <property name="cId" value="8"></property>
        <property name="cName" value="战鼓擂"></property>
    </bean>

                4》:获取bean对象,并调用对象的方法

/*方法一:id + 类*/
//获取IOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
Student studentTwo = ioc.getBean("studentTwo", Student.class);
System.out.println(studentTwo);


/*方法二:id*/
//获取IOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
Student studentTwo = ioc.getBean("studentTwo");
System.out.println(studentTwo);

/*方法三:类*/
//获取IOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
Student studentTwo = ioc.getBean(Student.class);
System.out.println(studentTwo);

/*方法四:类所实现的接口*/
//获取IOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
Student studentTwo = ioc.getBean(StudentInterface.class);
System.out.println(studentTwo);


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值