子 bean 的定义继承父定义的配置数据。子定义可以根据需要重写一些值,或者添加其他值。
编写HelloWorld.java
package com.example.spring; public class HelloWorld {
private String message1;
private String message2;
public void setMessage1(String message){
this.message1 = message;
}
public void setMessage2(String message){
this.message2 = message;
} public void getMessage1(){
System.out.println("Your Message1 : " + message1);
}
public void getMessage2(){
System.out.println("Your Message2 : " + message2);
}
}
编写HelloSpring.java
package com.example.spring; public class HelloSpring {
private String message1;
private String message2;
private String message3; public void setMessage1(String message){
this.message1 = message;
} public void setMessage2(String message){
this.message2 = message;
} public void setMessage3(String message){
this.message3 = message;
} public void getMessage1(){
System.out.println("Spring Message1 : " + message1);
} public void getMessage2(){
System.out.println("Spring Message2 : " + message2);
} public void getMessage3(){
System.out.println("Spring Message3 : " + message3);
}
}
编写Beans.xml,使用parent属性将“helloSpring”定义为“helloWorld”的子Bean,这个子Bean继承message2的属性,重写message1的属性,并且引入一个属性message3。
<?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="helloWorld" class="com.example.spring.HelloWorld">
<property name="message1" value="Hello World : message1"></property>
<property name="message2" value="Hello World : message2"/>
</bean> <bean id="helloSpring" class="com.example.spring.HelloSpring" parent="helloWorld">
<property name="message1" value="Hello Spring : message1"/>
<property name="message3" value="Hello Spring : message3"/>
</bean> </beans>
编写Application.java
package com.example.spring; import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application {
public static void main(String[] args) {
//bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml
//使用AbstractApplicationContext容器
AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml");
HelloWorld objA = (HelloWorld)context.getBean("helloWorld");
objA.getMessage1();
objA.getMessage2(); HelloSpring objB = (HelloSpring) context.getBean("helloSpring");
objB.getMessage1();
objB.getMessage2();
objB.getMessage3();
}
}
运行输出
Your Message1 : Hello World : message1
Your Message2 : Hello World : message2
Spring Message1 : Hello Spring : message1
Spring Message2 : Hello World : message2
Spring Message3 : Hello Spring : message3