Spring入門之Springbean定義的繼承
阿新 • • 發佈:2019-02-13
Spring中的bean之間的繼承和一般的po類繼承是不一樣的,他們之間的繼承不能簡單的使用extends關鍵字來實現
bean之間的繼承需要在xml配置檔案中配置
bean繼承例項:/h5>
//子類
public class Test {
private String msg1;
private String msg2;
private String msg3;
public String getMsg1() {
return msg1;
}
public void setMsg1(String msg1) {
this .msg1 = msg1;
}
public String getMsg2() {
return msg2;
}
public void setMsg2(String msg2) {
this.msg2 = msg2;
}
public String getMsg3() {
return msg3;
}
public void setMsg3(String msg3) {
this.msg3 = msg3;
}
}
//父類
public class ParentTest {
private String msg1;
private String msg2;
public String getMsg1() {
return msg1;
}
public void setMsg1(String msg1) {
this.msg1 = msg1;
}
public String getMsg2() {
return msg2;
}
public void setMsg2(String msg2) {
this.msg2 = msg2;
}
}
//xml配置檔案
<!-- 繼承的配置 -->
<bean id="test" class="org.spring.extendTest.Test" parent="parentTest">
<property name="msg1" value="test1" />
<property name="msg3" value="test3" />
</bean>
<bean id="parentTest" class="org.spring.extendTest.ParentTest">
<property name="msg1" value="pptest1" />
<property name="msg2" value="pptest2" />
</bean>
//測試主程式
public class TestMain {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Test parentTest = context.getBean("test",Test.class);
System.out.println("msg1->"+parentTest.getMsg1());
System.out.println("msg2->"+parentTest.getMsg2());
}
}