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

SpringDI_容器的继承

时间:2015-11-02 19:10:39      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

Person

package com.spring.extend;


public class Person {
    
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
}

student

package com.spring.extend;

public class Student extends Person {

    
}

 

ApplicationContext.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-2.5.xsd">
        
    <!--在父类中进行赋值,子类通过 parent属性继承父类的内容 --> 
    <bean id="person" class="com.spring.extend.Person">
        <property name="name" value="aaa"></property>
    </bean>
    
    <!-- 
        parent  实现了Spring容器内部的继承关系
     -->
     
    <bean id="student" class="com.spring.extend.Student" parent="person"></bean>    
    
    
    
    <!-- 
        因为java的继承机制,子类继承的父类的setXX方法,左右子类可以利用setXXX方法注入值
     -->    
    <bean id="person2" class="com.spring.extend.Person"></bean>
    
     <bean id="student2" class="com.spring.extend.Student">
         <property name="name" value="bbb"></property>
     </bean>    
        
        
        
</beans>

 

测试

package com.spring.extend.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.extend.Student;

public class ExtendsTest {
    
    @Test
    public void testDI_XML_constructor(){
        
        ApplicationContext context=
                new ClassPathXmlApplicationContext("applicationContext.xml");
        
//        Student student=(Student) context.getBean("student");
//        
//        System.out.println(student.getName());  //aaa
        
//        Student student=(Student) context.getBean("student2");
//        
//        System.out.println(student.getName());  //bbb
    }
    

}

 

SpringDI_容器的继承

标签:

原文地址:http://www.cnblogs.com/thinkpad/p/4930753.html

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