在基于spring框架开发的项目中,若是有多个bean都是一个类的实力,如配置多个数据源时,大部分配置的属性都同样,只有少部分不同,常常是copy上一个的定义,而后修改不同的地方。其实spring bean定义也能够和对象同样进行继承。java
示例以下:spring
<bean id="testBeanParent" abstract="true" class="com.wanzheng90.bean.TestBean"> <property name="param1" value="父参数1"/> <property name="param2" value="父参数2"/> </bean> <bean id="testBeanChild1" parent="testBeanParent"/> <bean id="testBeanChild2" parent="testBeanParent"> <property name="param1" value="子参数1"/> </bean>
testBeanParent是父bean,其中abstract=“true”表示testBeanParen不会被建立,相似于于抽象类。其中testBeanChild一、testBeanChild2继承了testBeanParent、,其中testBeanChild2从新对param1属性进行了配置,所以会覆盖testBeanParentapp
对param1属性属性的配置。框架
代码以下:函数
TestBean
this
public class TestBean { private String param1; private String param2; public String getParam1() { return param1; } public void setParam1(String param1) { this.param1 = param1; } public String getParam2() { return param2; } public void setParam2(String param2) { this.param2 = param2; } }
App:spa
public class App { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml"); TestBean testBeanChild1 = (TestBean) context.getBean("testBeanChild1"); System.out.println( testBeanChild1.getParam1()); System.out.println( testBeanChild1.getParam2()); TestBean testBeanChild2 = (TestBean) context.getBean("testBeanChild2"); System.out.println( testBeanChild2.getParam1()); System.out.println( testBeanChild2.getParam2()); } }
app main函数输出:code
父参数1 父参数2 子参数1 父参数2