package com.xiaohao.action;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; /**
* 需要导入dom4j的jar包
* @author 小浩
* @创建日期 2015-4-4
*/
public class BeanFactory { /**
* 保存容器中所有单例模式的bean实例,这里的hashMap是线程安全的
*
*/ private static Map<String,Object> beanPool=Collections.synchronizedMap(new HashMap<String,Object>());
//保存文件对应的Document对象
private Document document;
//保存配置文件里的根元素
private Element root; /**
* 构造方法,指定需要读取的文件的路径
* @param filePath
* @throws Exception
*/
public BeanFactory(String filePath) throws Exception{ //使用dom4j读取xml配置文件
SAXReader reader=new SAXReader();
document=reader.read(new File(filePath));
root=document.getRootElement();
//进行容器的初始化
initPool();
//初始化单例bean的属性
initProp(); } /**
* 获取指定的bean
* @param name
* @return
* @throws Exception
*/
public static Object getBean(String name) throws Exception {
Object target = beanPool.get(name);
//对于单例bean,容器已经初始化了所有的Bean实例
if(target.getClass() != String.class){
return target;
}else{
String clazz = (String)target;
//对于非单例的并未注入属性值
return Class.forName(clazz).newInstance();
} } /**
* 初始化容器中的所有单例bean
* */
private void initPool() throws Exception{
//遍历配置文件中的每个<bean ../>元素
for(Object obj:root.elements()){
Element beanElement = (Element)obj;
//获取Bean元素中的id属性
String beanId = beanElement.attributeValue("id");
//获取bean元素中的class属性
String beanClazz = beanElement.attributeValue("class");
//获取bean元素中的scope属性
String beanScope = beanElement.attributeValue("scope");
//如果scope属性不存在或为singleton
if(beanScope == null|| beanScope.equals("singleton")){
//以默认构造方法创建bean实例,并将其放入beanPool中
beanPool.put(beanId, Class.forName(beanClazz).newInstance()); //利用反射的技术
}else{
//对于非单例的,存放Bean实现类的类名
beanPool.put(beanId, beanClazz);
}
} } /**
* 初始化容器中的单例bean
* */
private void initProp() throws Exception{
//遍历配置文件中的所有bean元素,即根节点的子节点
for(Object object:root.elements()){
Element beanElement = (Element)object;
//获取Bean元素中的id属性
String beanId = beanElement.attributeValue("id");
//获取bean元素中的scope属性
String beanScope = beanElement.attributeValue("scope");
//如果scope属性不存在或为singleton
if(beanScope == null|| beanScope.equals("singleton")){
//取出beanPool的指定bean实例
Object bean = beanPool.get(beanId);
//遍历bean属性下的所有property属性
for(Object prop: beanElement.elements()){
Element probElement = (Element)prop;
//获取property的name属性
String propName = probElement.attributeValue("name");
//获取property的value属性
String propValue = probElement.attributeValue("value");
//获取property的ref属性
String propRef = probElement.attributeValue("ref");
//将属性名的首字母大写
String propNameCamelize = propName.substring(0,1).toUpperCase()
+propName.substring(1, propName.length());
//如果value值存在
if(propValue != null&&propValue.length()> 0){
//获取设置注入所需要的setter方法
java.lang.reflect.Method setter = bean.getClass().getMethod("set"+propNameCamelize, String.class);
//执行setter注入
setter.invoke(bean, propValue);
}
if(propRef != null&&propRef.length()> 0){
//取得需要被注入的bean实例
Object target = beanPool.get(propRef);
//如果不存在
if(target == null){
//此处处理单例bean依赖于非单例bean的情形
}
//定义设值注入需要的setter方法
Method setter = null;
//遍历target对象所实现的所有方法
for(Class superInterface: target.getClass().getInterfaces()){
try{
//获取设置注入所需要的setter方法
setter = bean.getClass().getMethod("set"+propNameCamelize, superInterface);
//如果成功获取,跳出循环
break;
}catch (Exception e) {
//如果没有找到就继续下次循环
continue;
}
}
//如果setter方法依然是null,直接取得target的实现类对应的setter方法
if(setter == null){
setter = bean.getClass().getMethod("set"+propNameCamelize, target.getClass());
}
//执行setter注入
setter.invoke(bean, target);
} }
} }
}
}

  

模拟Spring中applicationContext.xml配置文件初始化bean的过程的更多相关文章

  1. ssh整合思想初步 struts2与Spring的整合 struts2-spring-plugin-2.3.4.1.jar下载地址 自动加载Spring中的XML配置文件 Struts2下载地址

    首先需要JAR包 Spring整合Structs2的JAR包 struts2-spring-plugin-2.3.4.1.jar 下载地址 链接: https://pan.baidu.com/s/1o ...

  2. web.xml中配置Spring中applicationContext.xml的方式

    2011-11-08 16:29 web.xml中配置Spring中applicationContext.xml的方式 使用web.xml方式加载Spring时,获取Spring applicatio ...

  3. 关于Spring中applicationContext.xml配置错误“org/springframework/transaction/interceptor/TransactionInterceptor”的问题解决

    问题描述: 在配置spring的applicationContext.xml中的默认事务管理器的时候可能会出现这样的错误: Error occured processing XML 'org/spri ...

  4. Spring中applicationContext.xml详解

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  5. 关于spring的applicationContext.xml配置文件的ref和value之自我想法

    今天在做SSH的一个项目的时候,因为需要定时操作,所以就再sping里面加入了一个quartz的小定时框架,结果在运行时候,发生了一个小bug. Caused by: org.springframew ...

  6. Spring中applicationContext.xml的bean里的id和name属性区别

    转自:http://www.cnblogs.com/ztf2008/archive/2009/02/11/1388003.html <beans><bean id="per ...

  7. STS中applicationContext.xml配置文件

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  8. Spring中,applicationContext.xml 配置文件在web.xml中的配置详解

    一.首先写一下代码结构. 二.再看web.xml中的配置情况. <?xml version="1.0" encoding="UTF-8"?> < ...

  9. Spring中ApplicationContext加载机制和配置初始化

    Spring中ApplicationContext加载机制.        加载器目前有两种选择:ContextLoaderListener和ContextLoaderServlet.        ...

随机推荐

  1. Android Screen Orientation

    Ref:Android横竖屏切换小结 Ref:Android游戏开发之横竖屏的切换(二十七)

  2. python3 批量缩放图片为iphone5的640*1136以下

    try: from PIL import Image, ImageDraw, ImageFont, ImageEnhance except ImportError: import Image, Ima ...

  3. 用Pythonic方式来思考

    一门语言的编程习惯是由用户来确立的.这些年来,Python开发者用Pythonic这个形容词来描述那种符合特定风格的代码. 这种Pyhtonic风格,既不是严密的规范,也不是由编译器强加给开发者的规则 ...

  4. 改善程序与设计的55个具体做法 day4

    今天晚上回到小区门口,买了点冬枣,要结账的时候想起来,钥匙没带,落公司了! TNND,没办法再回趟公司,拿了钥匙,来回一个小时,汗~ 条款10:令operator=返回一个reference to * ...

  5. iOS 流媒体 基本使用 和方法注意

    项目里面需要添加视频方法   我自定义 选用的是 avplayer  没选择 MediaPlayer  原因很简单 , avplayer 会更容易扩展  有篇博客 也很好地说明了 使用avplayer ...

  6. Android AbsoluteLayout绝对布局

    绝对布局也叫坐标布局,指定元素的绝对位置,因为适应性很差,一般很少用到.可以使用RelativeLayout替代. 常用属性: android:layout_x --------组件x坐标 andro ...

  7. 【Flask模板】宏的概念和基本使用

    # 宏:模板中的宏跟python中的函数类似,可以传递参数,但是不能有返回值,可以将一些经常用到的代码片段放到宏中,然后把一些不固定的值抽取出来当成一个变量.使用宏的时候,参数可以为默认值.相关示例代 ...

  8. 剑指offer——求1+2+...+n

    方法一.通过在类的构造函数中执行加的过程. #include <iostream> using namespace std; class Base { public: Base(){n++ ...

  9. php中删除数组的第一个元素和最后一个元素的函数

    对于一个php数组,该如何删除该数组的第一个元素或者最后一个元素呢?其实这两个过程都可以通过php自带的函数 array_pop 和 array_shift 来完成,下面就具体介绍一下如何来操作. ( ...

  10. STL中流相关的输入输出符和get函数彻底总结:cin、cin.get()、cin.getline()、getline()、gets()等函数的用法

    我的总结: [首先:对于流来说,就把流看成一个中转的仓库,对流进行<<运算或>>运算或者get函数的运算都是指,把“流”中的数据“运送”到“内存变量”中去,还是把内存变量中的数 ...