简单模拟spring的容器管理bean

来源:java认证发布时间:2012-11-12 12:48:38java认证视频

package com.spring;

import java.io.IOException;

import java.net.URL;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.JDOMException;

import org.jdom.input.SAXBuilder;

import org.jdom.xpath.XPath;

import com.vo.BeanDefinition;

/**

* 简单模拟springClassPathXmlApppcationContext spring容器管理bean

*

* @author

*

*/

@SuppressWarnings“unchecked”

pubpc class MyApppcationContext

{

private List pst = new ArrayList();

private Map sigletons = new HashMap();

pubpc MyApppcationContextString fileName

{

this.readXMLfileName;

try

{

instanceBeans();

}

catch Exception e

{

e.printStackTrace();

}

}

/**

* 实例化所有bean

*

* @throws InstantiationException

* @throws IllegalAccessException

* @throws ClassNotFoundException

*/

private void instanceBeans() throws InstantiationException

IllegalAccessException ClassNotFoundException

{

for BeanDefinition bean pst

{

if null = bean.getClassName() && bean.getClassName().length() 0

sigletons.putbean.getId(), Class.forNamebean.getClassName())

.newInstance());

}

}

/**

* 读取xml配置

*

* @param fileName

*/

pubpc void readXMLString fileName

{

SAXBuilder builder = new SAXBuilder();

URL url = this.getClass().getClassLoader().getResourcefileName;

try

{

Document doc = builder.buildurl;

XPath xpath = XPath.newInstance“//ns:beans/ns:bean”;

xpath.addNamespace“ns”

“http://www.springframework.org/schema/beans”;

List beans = xpath.selectNodesdoc;

for Element bean beans

{

String id = bean.getAttributeValue“id”;

String className = bean.getAttributeValue“class”;

BeanDefinition beanDefinition = new BeanDefinitionid

className;

pst.addbeanDefinition;

}

}

catch JDOMException e

{

e.printStackTrace();

}

catch IOException e

{

e.printStackTrace();

}

}

/**

* 得到指定idbean

*

* @param id

* @return

*/

pubpc Object getBeanString id

{

return sigletons.getid;

}

}

测试:

@Test

pubpc void testMyUserService()

{

MyApppcationContext ctx = new MyApppcationContext“beans.xml”;

UserService us = UserService ctx.getBean“userService”;

us.print();

}

TAG: JavaJAVAjava

 -5-3-1-+1+3+5

评分:0

视频学习

我考网版权与免责声明

① 凡本网注明稿件来源为"原创"的所有文字、图片和音视频稿件,版权均属本网所有。任何媒体、网站或个人转载、链接转贴或以其他方式复制发表时必须注明"稿件来源:我考网",违者本网将依法追究责任;

② 本网部分稿件来源于网络,任何单位或个人认为我考网发布的内容可能涉嫌侵犯其合法权益,应该及时向我考网书面反馈,并提供身份证明、权属证明及详细侵权情况证明,我考网在收到上述法律文件后,将会尽快移除被控侵权内容。

最近更新

社区交流

考试问答