zoukankan      html  css  js  c++  java
  • 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"。那么是会生成父类的,可是假设有了,就不会实例化父类。

  • 相关阅读:
    Mybatis简单的入门之增删改查
    循环的角度求均值
    谈谈软件设计
    秒杀多线程第四篇 一个经典的多线程同步问题
    (转)dp动态规划分类详解
    P1006 传纸条
    P1005 矩阵取数游戏
    1D1D动态规划优化
    NOI 2009A 诗人小G
    P1078 文化之旅
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7102311.html
Copyright © 2011-2022 走看看