码迷,mamicode.com
首页 > 编程语言 > 详细

spring中 <bean parent=" "> parent属性的作用

时间:2017-08-18 19:49:13      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:cat   工程   tostring   framework   set   system   bsp   []   location   

第一步: 新建工程  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);
    }
}

 

第六步: 运行结果如下

技术分享

 

spring中 <bean parent=" "> parent属性的作用

标签:cat   工程   tostring   framework   set   system   bsp   []   location   

原文地址:http://www.cnblogs.com/beibidewomen/p/7391043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!