Spring IOC嵌套bean在模板覆盖属性值中

时间:2014-08-01 19:39:51

标签: java spring inversion-of-control

我有一个template bean,它有一个嵌套的bean。嵌套bean有两个重要属性,一个对其他3个bean定义有效,但它们有一个在每个bean中都有变化的secong属性。

我的模板看起来像这样。一个没有课程的豆子。

<bean id="myBeanTemplate" abstract="true" scope="prototype">
    <property name="school">        
        <bean class="com.model.School" scope="prototype">
            <property name="status" value="true"/><!--is all the same for all the child beans..->
            /*address=?? the property which is change across the children beans.. the property to  be set*/
        </bean>
    </property>
 </bean>    

这里我不设置addres属性只是因为它们在以下bean声明中有所不同,我想做的就是上面的bean模板和override the address property only。就像这样。

<bean id="myBeanForStudentsInSchool13" class="com.model.Students" parent="myBeanTemplate" scope="prototype">    
       here i want to set the address property to a value   
</bean>

<bean id="myBeanForStudentsInSchool23" class="com.model.Students" parent="myBeanTemplate" scope="prototype">    
       here i want to set the address property a different value    
</bean>

但是像嵌套的bean我不知道如何引用它......

更新

我被允许使用声明性配置......

非常感谢..

1 个答案:

答案 0 :(得分:4)

使用Java Config检查此解决方案。

学校模式:

public class School {

    private boolean status;
    private String address;

    // getters & setters

}

Bean模板:

public abstract class MyBeanTemplate {

    private School school;

    public School getSchool() {
        return school;
    }

    public void setSchool(School school) {
        this.school = school;
    }

}

学生班:

public class Students extends School {

}

Spring配置:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {

    @Bean
    public Students myBeanForStudentsInSchool13() {
        Students students = new Students();
        students.setAddress("myBeanForStudentsInSchool13");

        return students;
    }

    @Bean
    public Students myBeanForStudentsInSchool23() {
        Students students = new Students();
        students.setAddress("myBeanForStudentsInSchool23");

        return students;
    }
}

修改

对于XML配置,请检查此示例(注意子bean中的点):

<bean id="myBeanTemplate" abstract="true" class="com.beans.MyBeanTemplate">
    <property name="school">
        <bean class="com.model.School">
            <property name="status" value="true"/>
        </bean>
    </property>
</bean>

<bean id="myBeanForStudentsInSchool13" class="com.model.Students" parent="myBeanTemplate">    
    <property name="school.address" value="myBeanForStudentsInSchool13"/>
</bean>

<bean id="myBeanForStudentsInSchool23" class="com.model.Students" parent="myBeanTemplate">    
    <property name="school.address" value="myBeanForStudentsInSchool23"/>
</bean>

您还可以在此处查看更详细的答案:spring - constructor injection and overriding parent definition of nested bean