[java]代码库
public class SpringIOC {
private String XMLPath;
/**
* @param XMLPath
* 配置文件的路径
*/
public SpringIOC(String XMLPath) {
this.XMLPath = XMLPath;
}
public Object getBean(String beanId) throws Throwable {
// 1.解析配置文件
Document doc = this.loadXML();
// 2.根据beanId定位到<bean>标签
Element beanElement = this.getBeanElement(doc, beanId);
// 3.获取beanElement的class属性的值
String classPath = this.getClassPath(beanElement);
// 4.通过class属性值利用反射技术构造bean实例
Object obj = this.createObject(classPath);
// 5.使用beanUtils给对象设置
obj = this.setObeject(beanElement, obj);
return obj;
}
/**
* 加载xml配置文件
*
* @return
* @throws Throwable
*/
private Document loadXML() throws Throwable {
return new SAXReader().read(new File(XMLPath));
}
/**
* 根据beanId定位到对应的bean标签
*
* @param doc
* @param beanId
* @return Element
*/
private Element getBeanElement(Document doc, String beanId) {
return (Element) doc.selectSingleNode("//bean[@id='" + beanId + "']");
}
/**
* 得到beanElement的class属性值
*
* @param beanElement
* @return
*/
private String getClassPath(Element beanElement) {
return beanElement.attributeValue("class");
}
/**
* 通过class属性值利用反射技术构造bean实例
*
* @param classPath
* @return
*/
private Object createObject(String classPath) throws Throwable {
return Class.forName(classPath).newInstance();
}
/**
* 使用工具类beanUtils给对象设值
*
* @param obj
* @return
* @throws Throwable
*/
@SuppressWarnings("unchecked")
private Object setObeject(Element beanElement, Object obj) throws Throwable {
List<Element> list = beanElement.elements();
for (Element element : list) {
String name = element.attributeValue("name");
String value = element.attributeValue("value");
BeanUtils.setProperty(obj, name, value);
}
return obj;
}
}