Spring的继承

阅读更多
parent-init.xml


 

  
  	 	
  	 		parent
  	 	
  
  

spring-init.xml


 

  
  	 	
  	 		sub
  	 	
  


TestParent.xml
package org.frame.auth.init;


import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class TestParent {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//文档果然犀利啊.
		Resource resource = new ClassPathResource("parent-init.xml");
		BeanFactory xmf = new XmlBeanFactory(resource);
		Resource subResource = new ClassPathResource("spring-init.xml");
		BeanFactory subXmf = new XmlBeanFactory(subResource,xmf);
		InitBean initBean = (InitBean) subXmf.getBean("initBean");
		System.out.println(initBean.getName());//得到的是父.

		ApplicationContext ctx = new ClassPathXmlApplicationContext("parent-init.xml");

		ApplicationContext subctx = new ClassPathXmlApplicationContext(new String[]{"spring-init.xml"},ctx);
		InitBean initBeanb = (InitBean) subctx.getBean("initBean");
		System.out.println(initBeanb.getName());//得到的是子.
	}

}


这里展示了Spring 的BeanFactory的加载,有趣的是XmlBeanFactory加载是父容器类覆盖子容器类,而ApplicationContext加载是是子容器类覆盖父容器类,这个大家要注意的。
下面展示Spring Bean的parent属性。




	
		
			ycl
		
		
			yes
		
	

	
		
			天才
		
	




Person
package org.frame.base.parent;

public class Person {

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

	public String toString(){
		return name+":"+message;
	}

}

Message
package org.frame.base.parent;

public abstract class Message {

	private String name;
	private String message;
	public void setName(String name) {
		this.name = name;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String toString(){
		return name+":"+message;
	}

}


测试
package org.frame.base.parent;

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

public class TestParent {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ctx = new ClassPathXmlApplicationContext("parent.xml");
		Person pp =(Person)ctx.getBean("person");
		System.out.println(pp);
	}

}


这里的Message和Person完全没有关系,但是我在Spring Bean中指定了其父Bean,可见Spring的这个parent是属性的继承。大家可以定义属性,然后采用重定义覆写.

你可能感兴趣的:(Spring,Bean,XML,Java)