文章目录
Bean 定义继承
Spring Bean 定义的继承与 Java 类的继承无关,但是继承的概念是一样的。你可以定义一个父 bean 的定义作为模板和其他子 bean 就可以从父 bean 中继承所需的配置。
当你使用基于 XML 的配置元数据时,通过使用父属性,指定父 bean 作为该属性的值来表明子 bean 的定义。
Bean 定义继承代码
- Parent
public class Parent {
private String message1;
public Parent(){
System.out.println("parent");
}
public String getMessage1() {
return message1;
}
public void setMessage1(String message1) {
this.message1 = message1;
}
}
- Son
public class Son {
private String message1;
private String message2;
public Son(){
super();
System.out.println("son");
}
public String getMessage1() {
return message1;
}
public void setMessage1(String message1) {
this.message1 = message1;
}
public String getMessage2() {
return message2;
}
public void setMessage2(String message2) {
this.message2 = message2;
}
}
- 配置文件
<?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="parent" class="com.cc.study.parent.Parent">
<property name="message1" value="hello1"></property>
</bean>
<bean id="son" class="com.cc.study.parent.Son" parent="parent">
<property name="message2" value="hello2"></property>
</bean>
</beans>
- 测试
@Test
public void demo(){
String xmlPath = "parent.xml";
AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
Son son = applicationContext.getBean("son",Son.class);
System.out.println(son.getMessage1());
System.out.println(son.getMessage2());
System.out.println(Son.class.getSuperclass());
}
可以看出在初始化Son的时候会先初始化Parent.并且Son可以获取到Parent的方法。但是Spring Bean 定义的继承与 Java 类的继承无关,所以通过查看Son.class.getSuperclass(),发现Son和Parent之间是没有Java的那种继承关系。