`

Spring学习笔记(3)----编码剖析Spring管理Bean的原理

阅读更多
Xml代码 复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.         xmlns:context="http://www.springframework.org/schema/context"  
  5.         xmlns:tx="http://www.springframework.org/schema/tx"  
  6.         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
  7.                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd   
  8.                 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  9.         <bean id="userBean" class="com.szy.spring.implbean.UserBean" />  
  10. </beans>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:context="http://www.springframework.org/schema/context"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
		<bean id="userBean" class="com.szy.spring.implbean.UserBean" />
</beans>

 

Spring的配置文件中记录了类的包路径,因此我们首先是要读入配置文件。在配置文件中Bean有id和class两个属性,我们首先定义一个Bean类,包含这两个属性:

 

Java代码 复制代码
  1. package com.szy.spring.implbean;   
  2.   
  3. public class Bean   
  4. {   
  5.     private String id;   
  6.     private String className;   
  7.     public String getId()   
  8.     {   
  9.         return id;   
  10.     }   
  11.     public void setId(String id)   
  12.     {   
  13.         this.id = id;   
  14.     }   
  15.     public String getClassName()   
  16.     {   
  17.         return className;   
  18.     }   
  19.     public void setClassName(String className)   
  20.     {   
  21.         this.className = className;   
  22.     }   
  23.        
  24. }   
  25.    
package com.szy.spring.implbean;

public class Bean
{
	private String id;
	private String className;
	public String getId()
	{
		return id;
	}
	public void setId(String id)
	{
		this.id = id;
	}
	public String getClassName()
	{
		return className;
	}
	public void setClassName(String className)
	{
		this.className = className;
	}
	
}
 

由于配置文件是xml文件,在这里使用Jdom包操作xml文件,读入配置文件中的Bean信息。

Java代码 复制代码
  1. /**  
  2.      * 读取xml配置文件  
  3.      * @param fileName 配置文件名  
  4.      */  
  5.     private void readXML(String fileName)   
  6.     {   
  7.         // 寻找配置文件   
  8.         URL xmlPath = this.getClass().getClassLoader().getResource(fileName);   
  9.         Document doc = null;   
  10.         Element root = null;   
  11.         try  
  12.         {   
  13.             SAXBuilder sb = new SAXBuilder(false);   
  14.             doc = sb.build(new FileInputStream(new File(xmlPath.toURI())));   
  15.             // 设置命名空间   
  16.             Namespace xhtml = Namespace.getNamespace("xhtml",   
  17.                     "http://www.springframework.org/schema/beans");   
  18.             root = doc.getRootElement(); // 获取根元素   
  19.             List<Element> list = root.getChildren("bean", xhtml); //获取全部bean节点   
  20.             for (Element element : list)// 遍历节点,取得每个节点的属性   
  21.             {   
  22.                 String id = element.getAttributeValue("id");   
  23.                 String className = element.getAttributeValue("class");   
  24.                 Bean bean = new Bean();   
  25.                 bean.setId(id);   
  26.                 bean.setClassName(className);   
  27.                 beanList.add(bean);   
  28.             }   
  29.         } catch (Exception e)   
  30.         {   
  31.             e.printStackTrace();   
  32.         }   
  33.   
  34.     }  
/**
	 * 读取xml配置文件
	 * @param fileName 配置文件名
	 */
	private void readXML(String fileName)
	{
		// 寻找配置文件
		URL xmlPath = this.getClass().getClassLoader().getResource(fileName);
		Document doc = null;
		Element root = null;
		try
		{
			SAXBuilder sb = new SAXBuilder(false);
			doc = sb.build(new FileInputStream(new File(xmlPath.toURI())));
			// 设置命名空间
			Namespace xhtml = Namespace.getNamespace("xhtml",
					"http://www.springframework.org/schema/beans");
			root = doc.getRootElement(); // 获取根元素
			List<Element> list = root.getChildren("bean", xhtml); //获取全部bean节点
			for (Element element : list)// 遍历节点,取得每个节点的属性
			{
				String id = element.getAttributeValue("id");
				String className = element.getAttributeValue("class");
				Bean bean = new Bean();
				bean.setId(id);
				bean.setClassName(className);
				beanList.add(bean);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}

	}

 

 其中beanList是一个List对象,因为在配置文件中存在很多Bean。

 

得到了所有的Bean对象后,下面就实例化每个Bean对象,结果存放在Map对象中。

 

Java代码 复制代码
  1. /**  
  2.      * bean的实例化  
  3.      */  
  4.     private void instanceBeans()   
  5.     {   
  6.         for (Bean bean : beanList)   
  7.         {   
  8.             try  
  9.             {   
  10.                 if (bean.getClassName() != null && !"".equals(bean.getClassName().trim()))   
  11.                     beanObject.put(bean.getId(), Class.forName(bean.getClassName()).newInstance());   
  12.             } catch (Exception e)   
  13.             {   
  14.                 e.printStackTrace();   
  15.             }   
  16.         }   
  17.   
  18.     }  
/**
	 * bean的实例化
	 */
	private void instanceBeans()
	{
		for (Bean bean : beanList)
		{
			try
			{
				if (bean.getClassName() != null && !"".equals(bean.getClassName().trim()))
					beanObject.put(bean.getId(), Class.forName(bean.getClassName()).newInstance());
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}

	}

 其中beanObject为Map对象。

 

最后再加入一个方法,方便外部能获取Map中的对象

Java代码 复制代码
  1. /**  
  2.      * 获取bean实例  
  3.      * @param beanName 配置文件中bean的Id  
  4.      * @return  
  5.      */  
  6.     public Object getBean(String beanName)   
  7.     {   
  8.         return this.beanObject.get(beanName);   
  9.     }  
/**
	 * 获取bean实例
	 * @param beanName 配置文件中bean的Id
	 * @return
	 */
	public Object getBean(String beanName)
	{
		return this.beanObject.get(beanName);
	}

 完整的MyClassPathXMLApplicationContext见附件中的代码。

 

下面测试MyClassPathXMLApplicationContext类。

Java代码 复制代码
  1. @Test  
  2.     public void testMethod() throws Exception   
  3.     {   
  4.         //读取配置文件   
  5.         MyClassPathXMLApplicationContext ctx=new MyClassPathXMLApplicationContext("applicationContext.xml");   
  6.         //获取UserBean的实例   
  7.         PersonBean bean=(PersonBean)ctx.getBean("userBean");   
  8.         //调用方法   
  9.         bean.show();   
  10.     }  
@Test
	public void testMethod() throws Exception
	{
		//读取配置文件
		MyClassPathXMLApplicationContext ctx=new MyClassPathXMLApplicationContext("applicationContext.xml");
		//获取UserBean的实例
		PersonBean bean=(PersonBean)ctx.getBean("userBean");
		//调用方法
		bean.show();
	}

 

输出结果

结果代码 复制代码
  1. Hello Kuka  
Hello Kuka

 

成功。

上面仅是简单的演示了Spring管理Bean的原理,但是在实际操作中还需要考虑很对其它因素。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics