Abstract, parent analysis in spring configuration

1: Analysis

When we define the bean, there may be multiple beans with the same properties, and the values ​​we want to give to these same properties are also the same. Normally, we need to repeat the configuration many times. Spring abstract=truehelps us solve this by providing The problem is that abstract=true is actually a configuration of encapsulating properties, not configuring beans. After the configuration is completed, if our real beans want to be used directly instead of being configured repeatedly, they can be used in parent=”公共配置的bean名称“a way.

2: Examples

2.1: Define Class 1

There nameproperty, age, hobby, :

public class MyCls1 {
    
    
    private String name;
    private String age;
    private String hobby;

    ...getter setter tostring...
}

2.2: Define Class 2

There properties, name, age, gender, and 2.1:定义类1the class name and age are defined repeating properties:

public class MyCls2 {
    
    
    private String name;
    private String age;
    private String gender;

    ...getter setter tostring...
}

2.3: Define common configuration

<bean id="basePropConfig" abstract="true">
    <property name="name" value="张三"/>
    <property name="age" value="20"/>
</bean>

2.4: Define 2 beans

<bean id="cls1" class="yudaosourcecode.abstractandparent.MyCls1" parent="basePropConfig">
    <property name="hobby" value="篮球"/>
</bean>
<bean id="cls2" class="yudaosourcecode.abstractandparent.MyCls2" parent="basePropConfig">
    <property name="gender" value=""/>
</bean>

2.5: Complete configuration

<?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="basePropConfig" abstract="true">
        <property name="name" value="张三"/>
        <property name="age" value="20"/>
    </bean>

    <bean id="cls1" class="yudaosourcecode.abstractandparent.MyCls1" parent="basePropConfig">
        <property name="hobby" value="篮球"/>
    </bean>
    <bean id="cls2" class="yudaosourcecode.abstractandparent.MyCls2" parent="basePropConfig">
        <property name="gender" value=""/>
    </bean>
</beans>

2.6: Test code

@Test
public void testAbstractAndParent() {
    
    
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:abstractandparent.xml");
    System.out.println(ac.getBean("cls1", MyCls1.class));
    System.out.println(ac.getBean("cls2", MyCls2.class));
}

run:

{"age":"20","hobby":"篮球","name":"张三"}
{"age":"20","gender":"男","name":"张三"}

You can see that the public properties have been inherited.

Guess you like

Origin blog.csdn.net/wang0907/article/details/114291605