spring中 <bean parent=" "> parent属性的作用
第一步: 新建工程 SecondSpring
文件目录结构如下:
第二步:导入spring 相应的jar包
过程略...
第三步: 新建类
ParentClass.java
package com.xuzhiwen.spring7; public class ParentClass { public String name; public int age; public String hobby; public void setHobby(String hobby) { this.hobby = hobby; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "ParentClass [name=" + name + ", age=" + age + ", hobby=" + hobby + "]"; } }
第四步:新建spring 配置文件
common.xml
<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-2.5.xsd"> <import resource="xmlfolder/app1.xml" /> <import resource="xmlfolder/innerbean.xml" /> <import resource="xmlfolder/singleton.xml" /> <import resource="xmlfolder/annotation.xml" /> <import resource="xmlfolder/gather.xml" /> <import resource="xmlfolder/date.xml" /> <import resource="xmlfolder/db.xml" /> <import resource="xmlfolder/parent.xml" /> </beans>
parent.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="parentClass" class="com.xuzhiwen.spring7.ParentClass"> <property name="age" value="22" /> <property name="name" value="xuzhiwen" /> </bean> <!-- sonClass相当于一个虚拟出来的类,因为没有反射的路径 --> <bean id="sonClass" parent="parentClass"> <property name="hobby" value="singing" /> </bean> </beans>
第五步: 新建测试类
package com.xuzhiwen.spring7; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("common.xml"); ParentClass test = (ParentClass) app.getBean("sonClass"); System.out.println(test); } }
第六步: 运行结果如下