spring中abstract bean的用法

什么是abstract bean?简单来说,就是在java中的继承时候,所要用到的父类。

案例文件结构:


其中Person类为父类,Student类为子类,其具体类为:

package com.test.mySpring;

public class Person {
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	protected String name;
	protected int age;
	
}

然后在Student类中增加了一个属性学号:

package com.test.mySpring;

public class Student extends Person{
	String no;

	public String getNo() {
		return no;
	}

	public void setNo(String no) {
		this.no = no;
	}

}

测试类:

package com.test.mySpring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import com.test.SpringGetSet.School;

public class TestCase {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BeanFactory factory=new XmlBeanFactory(new ClassPathResource("com/test/mySpring/beans.xml"));
		//Person p=(Person)factory.getBean("person");
		//System.out.println(p.getName()+" "+p.getAge());
		
		Student s=(Student)factory.getBean("student");
		System.out.println(s.getName()+" "+s.getAge()+" "+s.getNo());
	}

}

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-2.5.xsd">

    <bean id="person" class="com.test.mySpring.Person" abstract="true">
        <property name="name" value="李白" />
        <property name="age" value="40" />
    </bean>
    
    <bean id="student" class="com.test.mySpring.Student" parent="person">
        <property name="no" value="sa12011106"/>
    </bean>
    
</beans>


输出结果:



分析:我们可以看到,在beans.xml中,如果没有abstract="true",那么是会生成父类的,但是如果有了,就不会实例化父类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值