Spring-Bean-配置bean-案例一:(parent)通过继承实现bean配置信息的重用

案例一:(parent)通过继承实现bean配置信息的重用

(1)创建一个类

public class Person {
    private String name;
    private Integer age;
    private String gender;

    public Person() {
    }

    public Person(String name, Integer age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

(2)配置文件

<bean id="person" class="com.orz.spring.bean.Person">
    <property name="name" value="李华"/>
    <property name="age" value="18"/>
    <property name="gender" value="男"/>
</bean>

<!--除了姓名,其他都一样,可以考虑使用继承   -->
<bean id="person2" class="com.orz.spring.bean.Person" parent="person">
    <property name="name" value="张三"/>
</bean>

(3)测试

@Test
public void test1()
{
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
    Person person = applicationContext.getBean("person", Person.class);
    Person person2 = applicationContext.getBean("person2", Person.class);
    System.out.println(person);
    System.out.println(person2);
}

(4)结果

Person{name='李华', age=18, gender='男'}

Person{name='张三', age=18, gender='男'}

 

 

posted @ 2020-10-19 14:14  orz江小鱼  阅读(187)  评论(0编辑  收藏  举报