栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Spring框架01】手动模拟IOC容器

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Spring框架01】手动模拟IOC容器

org.dom4j

dom4j

2.1.1

jaxen

jaxen

1.1.6

[](()xml配置


这里最好还是写全生成小绿叶子好一点,不然后面test就报错!!!

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

[](()测试类


public class HelloService {

public void test(){

System.out.println(“HelloService…successful!!!”);

}

}

[](()模拟ioc


[](()1…application.java 接口

public interface ApplicationContext {

public Object getBean(String id);

}

[](()2.接口实现类

public class lcyApplicationContext implements ApplicationContext {

private String xmlPath;

private List lcyBeans = new ArrayList<>();//存放解析结果

private Map beanMap = new HashMap<>();//存放反射生成的bean

public lcyApplicationContext(String xmlPath){

this.xmlPath=xmlPath;

readXml();

initBean();

}

private void initBean() {

//开始反射生成bean

if(lcyBeans.size()>0){

for(LcyBean lcyBean:lcyBeans){

String id=lcyBean.getId();

String clazz=lcyBean.getClazz();

try {

beanMap.put(id,Class.forName(clazz).newInstance());

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

}

}

private void readXml() {

if(null!=xmlPath&&“”!=xmlPath){

//创建解析对象

SAXReader reader = new SAXReader();

try {

URL url = this.getClass().getClassLoader().getResource(xmlPath);

Document document = reader.read(url);

List list=document.selectNodes(“//beans/bean”);

for(Iterator iter =list.iterator();iter.hasNext()

{

Element e = (Element)iter.next();

System.out.println(e.attributeValue(“id”) + e.attributeValue(“class”));

//存入集合

LcyBean lcyBean= new LcyBean();

lcyBean.setId(e.attributeValue(“id”));

lcyBean.setClazz(e.attributeValue(“class”));

lcyBeans.add(lcyBean);

}

} catch (DocumentException e) {

e.printStackTrace();

System.err.println(“文件找不到”);

}

}

else{

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/842059.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号