【java spring】内部bean

我们知道想要把一个bean对象注入到一个属性上,可以用ref的方式来引用bean的id,但是这样子做会容易使得xml杂乱,如果ref引用过多,我们需要定义很多个bean,需要起很多个id名。本章介绍的内部bean可以解决这样的问题,内部bean是匿名的,而且直接出现在需要它的地方,这样一来我们不必为命名而操心,整个xml结构也清晰了起来。
inner_bean.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="master" class="upc.yqs.Master">
        <property name="age" value="10"></property>
        <property name="pets">
            <list>
                <bean class="upc.yqs.Pet">
                    <property name="name" value=""></property>
                </bean>
                <bean class="upc.yqs.Pet">
                    <property name="name" value=""></property>
                </bean>
            </list>
        </property>
    </bean>
</beans>

Master类:

import java.util.List;

public class Master
{
    public int age;
    List<Pet> pets;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<Pet> getPets() {
        return pets;
    }

    public void setPets(List<Pet> pets) {
        this.pets = pets;
    }
}

Pet类:

public class Pet
{
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void sound()
    {
        System.out.println(name+"叫了一下");
    }
}

测试类:

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import upc.yqs.Master;
import upc.yqs.Pet;

import java.util.Iterator;

public class InnerBeanTest
{
    public ApplicationContext context;
    @Before
    public void getContext()
    {
        context= new ClassPathXmlApplicationContext("inner_bean.xml");
    }
    @Test
    public void innerBeanTest()
    {
        Master master=(Master) context.getBean("master");
        Iterator<Pet> it=master.getPets().iterator();
        while (it.hasNext())
        {
            it.next().sound();
        }
    }
}

输出:

猫叫了一下
狗叫了一下
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值