子 bean 的定义继承父定义的配置数据。子定义可以根据需要重写一些值,或者添加其他值。
编写HelloWorld.java
1 package com.example.spring; 2 3 public class HelloWorld { 4 private String message1; 5 private String message2; 6 public void setMessage1(String message){ 7 this.message1 = message; 8 } 9 public void setMessage2(String message){ 10 this.message2 = message; 11 } 12 13 public void getMessage1(){ 14 System.out.println("Your Message1 : " + message1); 15 } 16 public void getMessage2(){ 17 System.out.println("Your Message2 : " + message2); 18 } 19 }
编写HelloSpring.java
1 package com.example.spring; 2 3 public class HelloSpring { 4 private String message1; 5 private String message2; 6 private String message3; 7 8 public void setMessage1(String message){ 9 this.message1 = message; 10 } 11 12 public void setMessage2(String message){ 13 this.message2 = message; 14 } 15 16 public void setMessage3(String message){ 17 this.message3 = message; 18 } 19 20 public void getMessage1(){ 21 System.out.println("Spring Message1 : " + message1); 22 } 23 24 public void getMessage2(){ 25 System.out.println("Spring Message2 : " + message2); 26 } 27 28 public void getMessage3(){ 29 System.out.println("Spring Message3 : " + message3); 30 } 31 }
编写Beans.xml,使用parent属性将“helloSpring”定义为“helloWorld”的子Bean,这个子Bean继承message2的属性,重写message1的属性,并且引入一个属性message3。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean id="helloWorld" class="com.example.spring.HelloWorld"> 7 <property name="message1" value="Hello World : message1"></property> 8 <property name="message2" value="Hello World : message2"/> 9 </bean> 10 11 <bean id="helloSpring" class="com.example.spring.HelloSpring" parent="helloWorld"> 12 <property name="message1" value="Hello Spring : message1"/> 13 <property name="message3" value="Hello Spring : message3"/> 14 </bean> 15 16 </beans>
编写Application.java
1 package com.example.spring; 2 3 import org.springframework.context.support.AbstractApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class Application { 7 public static void main(String[] args) { 8 //bean配置文件所在位置 D:\IdeaProjects\spring\src\Beans.xml 9 //使用AbstractApplicationContext容器 10 AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:D:\IdeaProjects\spring\src\Beans.xml"); 11 HelloWorld objA = (HelloWorld)context.getBean("helloWorld"); 12 objA.getMessage1(); 13 objA.getMessage2(); 14 15 HelloSpring objB = (HelloSpring) context.getBean("helloSpring"); 16 objB.getMessage1(); 17 objB.getMessage2(); 18 objB.getMessage3(); 19 } 20 }
运行输出
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