Learn Spring - Bean配置继承(配置重用)
Posted
关于Bean配置继承
为了Bean
配置的复用,Spring
中有Bean
配置继承的概念。通过parent
属性标识从哪个Bean
继承配置信息。类似于面向对象里的概念,子Bean
可以覆盖父Bean
的配置。还可以设置Bean
配置的 abstract
属性为true
,将该Bean
设置为一个模板,其它Bean
继承它的模板配置。类似于Java
中的抽象类,abstract
的Bean
不允许实例化。
Example
目录结构
Code
Beans.xml
<?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-3.0.xsd">
<bean id = "helloWorld" class = "me.coolcodes.HelloWorld">
<property name = "message1" value = "Message1"/>
<property name = "message2" value = "Message2"/>
</bean>
<bean id="helloSpring" class="me.coolcodes.HelloSpring" parent="helloWorld">
<property name = "message3" value = "Message3"/>
<property name = "message4" value="Message4"></property>
</bean>
</beans>
helloSpring
继承了helloWorld
的配置(即message1
和 message2
)
HelloWorld.java
package me.coolcodes;
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("World Message : " + message1);
}
public void getMessage2(){
System.out.println("World Message : " + message2);
}
}
HelloSpring.java
package me.coolcodes;
public class HelloSpring {
private String message1;
private String message2;
private String message3;
private String message4;
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 setMessage4(String message){
this.message4 = message;
}
public void getMessage1(){
System.out.println("Spring Message : " + message1);
}
public void getMessage2(){
System.out.println("Spring Message : " + message2);
}
public void getMessage3(){
System.out.println("Spring Message : " + message3);
}
public void getMessage4(){
System.out.println("Spring Message : " + message4);
}
}
Main.java
package me.coolcodes;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
HelloSpring objB = (HelloSpring) context.getBean("helloSpring");
objA.getMessage1();
objA.getMessage2();
objB.getMessage1();
objB.getMessage2();
objB.getMessage3();
objB.getMessage4();
}
}
分别输出HelloWorld
的message1
和 message2
。HelloSpring
的message1
、message2
、message3
、message4
。
结果
HelloSpring
的message1
和message2
的值继承自HelloWorld
。