您的位置:首页 > 其它

反射笔记:一种简单的基于配置文件的IoC实现

2014-11-18 21:29 459 查看
换spring了。哈哈

/**
*
*/
package boa.ioc;

import java.util.HashMap;
import java.util.Map;

/**解析配置文件,取得数据,提供数据以产生对象。
*
* @author zhangdapeng
* @version 1.0,2013年10月21日
* @since   1.0
*/
public class Bean {
/* Bean Id */
private String id;
/* Bean Class */
private String type;
/* Bean Property */
private Map<String, Object> properties = new HashMap<String, Object>();
public Bean() {
// TODO Auto-generated constructor stub
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public Map<String, Object> getProperties() {
return properties;
}

public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}

}


package boa.ioc;

import java.lang.reflect.Method;
import java.util.Map;

import boa.context.DecoderContext;
import boa.exception.ApplicationException;
/**
*
* @author zhangdapeng
* @version 1.0,2013年10月23日
* @since   1.0
*/
public class BeanFactory {
private static Map<String, Bean> beanMap =  null;

public BeanFactory() throws Exception {
}

public static Object getBean(String id)throws ApplicationException {
Bean bean = beanMap.get(id);
if(bean==null){
return null;
}
Object obj = null;
try {
obj = BeanFactory.newInstance(bean.getType());
} catch (Exception e) {
throw new ApplicationException(e);
}
for (String key : bean.getProperties().keySet()) {
try {
setProperty(obj, key, bean.getProperties().get(key));
} catch (Exception e) {
throw new ApplicationException(e);
}
}
return obj;
}

public static Object newInstance(String className) throws Exception {
Class<?> cls = null;
Object obj = null;
cls = Class.forName(className);
obj = cls.newInstance();
return obj;
}

public static void setProperty(Object obj, String name, Object value) throws Exception {
Class<? extends Object> clazz = obj.getClass();
String methodName = returnSetMethodName(name);
Method[] ms = clazz.getMethods();
for (Method m : ms) {
if (m.getName().equals(methodName)) {
if (m.getParameterTypes().length == 1) {
Class<?> clazzParameterType = m.getParameterTypes()[0];
setFieldValue(clazzParameterType.getName(), value, m, obj);
break;
}
}
}
}

private static void setFieldValue(String name, Object value, Method m, Object obj) throws Exception {
if (name.equals(int.class.getName())) {
value = new Integer(Integer.parseInt(value.toString()));
m.invoke(obj, value);
return;
}
if(value.getClass().getName().equals(Ref.class.getName())){
Ref ref=(Ref) value;
value=BeanFactory.getBean(ref.getLocal());
}
m.invoke(obj, value);
}

private static String returnSetMethodName(String name) {
name = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
return "set" + name;
}
public static Map<String, Bean> getBeanMap() {
return beanMap;
}

public static void setBeanMap(Map<String, Bean> beanMap) {
BeanFactory.beanMap = beanMap;
}

public static void main(String[] args) {
try {
DecoderContext decoder=(DecoderContext) BeanFactory.getBean("decoderContext");
System.out.println(decoder.getDirList());
} catch (Exception e) {
e.printStackTrace();
}
}

}


/**
*
*/
package boa.ioc;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
* @author zhangdapeng
* @version 1.0,2013年10月23日
* @since 1.0
*/
public class BeanResource {

/**
*
*/
public BeanResource() {
}

public static Map<String, Bean> load(String path){
Log logger = LogFactory.getLog(BeanResource.class);
SAXReader reader = new SAXReader();
reader.setEncoding("UTF-8");
Document doc = null;
try {
doc = reader.read(new File(path));
} catch (DocumentException e) {
logger.error(e.getStackTrace());
}
// doc.setXMLEncoding("UTF-8");
Map<String, Bean> beanMap = new HashMap<String, Bean>();
Bean bean = null;
Map<String, Object> properties = null;
Element firstEle = doc.getRootElement();
for (Iterator<Element> firstIter = firstEle.elementIterator(); firstIter.hasNext();) {
bean = new Bean();
Element secondEle = firstIter.next();
bean.setId(secondEle.attributeValue("id").trim());
bean.setType(secondEle.attributeValue("class").trim());

properties = new HashMap<String, Object>();
for (Iterator<Element> secIter = secondEle.elementIterator(); secIter.hasNext();) {
Element thirdEle = secIter.next();
if (thirdEle.hasContent()) {
Element fourthEle = (Element) thirdEle.elementIterator().next();
if (fourthEle.getName().equals("list")) {
List<String> dirList = new ArrayList<String>();
for (Iterator<Element> fifthIter = fourthEle.elementIterator(); fifthIter.hasNext();) {
Element fifthEle = fifthIter.next();
dirList.add(fifthEle.getTextTrim());
}
properties.put(thirdEle.attributeValue("name").trim(), dirList);
}

if (fourthEle.getName().equals("ref")) {
Ref ref = new Ref();
Attribute name;
for (Iterator<Attribute> fourAttr = fourthEle.attributeIterator(); fourAttr.hasNext();) {
name = fourAttr.next();
if (name.getName().equals("local")) {
ref.setLocal(name.getText());
}
}
properties.put(thirdEle.attributeValue("name").trim(), ref);
}

if (fourthEle.getName().equals("map")) {
Map map = new HashMap();
String key = null;
String value = null;
Attribute name = null;
for (Iterator<Element> fifthIter = fourthEle.elementIterator(); fifthIter.hasNext();) {
Element fifthEle = fifthIter.next();
Pairs pairs = new Pairs();
for (Iterator<Attribute> attr = fifthEle.attributeIterator(); attr.hasNext();) {
name = attr.next();
if (name.getName().equals("key")) {
key = name.getValue().trim();
}
if (name.getName().equals("value")) {
value = name.getValue().trim();
}
}
if (key == null || value == null) {
logger.error("name:" + name + ".格式不对!");
System.exit(1);
}
map.put(key, value);
}

properties.put(thirdEle.attributeValue("name").trim(), map);
}

continue;
}
properties.put(thirdEle.attributeValue("name").trim(), thirdEle.attributeValue("value").trim());
}
bean.setProperties(properties);
beanMap.put(bean.getId(), bean);
}
return beanMap;
}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
BeanResource.load("./config/beans.xml");
}

}


/**
*
*/
package boa.ioc;

/**
* @author zhangdapeng
* @version 1.0,2013年11月3日
* @since 1.0
*/
public class Pairs {
private String key = null;
private String value = null;

/**
*
*/
public Pairs() {
}

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}
}


/**
*
*/
package boa.ioc;

/**
* @author zhangdapeng
* @version 1.0,2013年10月25日
* @since   1.0
*/
public class Ref {
private String local;
/**
*
*/
public Ref() {
// TODO Auto-generated constructor stub
}
public String getLocal() {
return local;
}
public void setLocal(String local) {
this.local = local;
}

}
xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="appContextConfig" class="boa.context.AppContextConfig">
<property name="dirList"><!-- 监控的根目录,绝对路径 -->
<list>
<value>e:/data</value>
</list>
</property>
<property name="regex"><!-- 正则表达式,用于匹配文件名 -->
<map>
<entry key="some1" value=".*" />
</map>
</property>
</bean>
<bean id="decoderContext" class="boa.context.DecoderContext">
<!-- <property name="decoder"> <ref local="decoders"></ref> </property> -->
<property name="service">
<ref local="riskWarnService"></ref>
</property>
<!-- <property name="task"> <ref local="riskWarnTask"></ref> </property> -->
</bean>

</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐