Java代码实现依赖注入
http://zhangjunhd.blog.51cto.com/113473/126545
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="me" class="com.zj.ioc.di.imp.Person">
<property name="name">
<value>ZJ</value>
</property>
<property name="age">
<value>26</value>
</property>
<property name="height">
<value>1.78</value>
</property>
</bean>
<bean id="you" class="com.zj.ioc.di.imp.Person">
<property name="name">
<value>Mary</value>
</property>
<property name="age">
<value>27</value>
</property>
<property name="height">
<value>1.66</value>
</property>
</bean>
<bean id="myList" class="com.zj.ioc.di.imp.ListOne">
<property name="msg">
<list>
<value>java</value>
<value>c</value>
<value>windows</value>
</list>
</property>
</bean>
<bean id="mySet" class="com.zj.ioc.di.imp.SetOne">
<property name="msg">
<set>
<value>tom</value>
<value>cat</value>
<value>dog</value>
</set>
</property>
</bean>
<bean id="myMap" class="com.zj.ioc.di.imp.MapOne">
<property name="msg">
<map>
<entry key="c">
<value>CHINA</value>
</entry>
<entry key="j">
<value>JAPAN</value>
</entry>
<entry key="k">
<value>KOREA</value>
</entry>
</map>
</property>
</bean>
<bean id="us" class="com.zj.ioc.di.imp.Persons">
<property name="i">
<ref bean="me" />
</property>
<property name="u">
<ref bean="you" />
</property>
</bean>
</beans>
|
package com.zj.ioc.di.imp;
public class Person {
private String name;
private int age;
private float height;
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
public float getHeight() {return height;}
public void setHeight(float height) {this.height = height;}
}
|
package com.zj.ioc.di.imp;
import java.util.List;
public class ListOne {
private List<String> msg;
public List<String> getMsg() {return msg;}
public void setMsg(List<String> msg) {this.msg = msg;}
}
|
package com.zj.ioc.di.imp;
import java.util.Set;
public class SetOne {
private Set<String> msg;
public Set<String> getMsg() {return msg;}
public void setMsg(Set<String> msg) {this.msg = msg;}
}
|
package com.zj.ioc.di.imp;
import java.util.Map;
public class MapOne {
private Map<String,String> msg;
public Map<String, String> getMsg() {return msg;}
public void setMsg(Map<String, String> msg) {this.msg = msg;}
}
|
package com.zj.ioc.di.imp;
public class Persons {
private Person i;
private Person u;
public Person getI() {return i;}
public void setI(Person i) {this.i = i;}
public Person getU() {return u;}
public void setU(Person u) {this.u = u;}
}
|
private Map<String, Object> beanMap = new HashMap<String, Object>();
……
public Object getBean(String beanId) {
Object obj = beanMap.get(beanId);
return obj;
}
|
BeanFactory factory = new BeanFactory();
factory.init("setting.xml");
Person p1 = (Person) factory.getBean("me");
|
public void init(String xmlUri) throws Exception {
SAXReader saxReader = new SAXReader();
File file = new File(xmlUri);
try {
saxReader.addHandler("/beans/bean", new BeanHandler());
saxReader.read(file);
} catch (DocumentException e) {
System.out.println(e.getMessage());
}
}
|
private class BeanHandler implements ElementHandler {
Object obj = null;
public void .Start(ElementPath path) {
Element beanElement = path.getCurrent();
Attribute classAttribute = beanElement.attribute("class");
Class<?> bean = null;
try {
bean = Class.forName(classAttribute.getText());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Field fields[] = bean.getDeclaredFields();
Map<String, Field> mapField = new HashMap<String, Field>();
for (Field field : fields)
mapField.put(field.getName(), field);
try {
obj = bean.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
path.addHandler("property", new PropertyHandler(mapField, obj));
}
public void .End(ElementPath path) {
Element beanElement = path.getCurrent();
Attribute idAttribute = beanElement.attribute("id");
beanMap.put(idAttribute.getText(), obj);
path.removeHandler("property");
}
}
|
private class PropertyHandler implements ElementHandler {
Map<String, Field> mapField;
Object obj;
public PropertyHandler(Map<String, Field> mapField, Object obj) {
this.mapField = mapField;
this.obj = obj;
}
public void .Start(ElementPath path) {
Element propertyElement = path.getCurrent();
Attribute nameAttribute = propertyElement.attribute("name");
path.addHandler("value", new ValueHandler(mapField, obj,
nameAttribute));
path.addHandler("list", new ListHandler(mapField, obj,
nameAttribute));
path.addHandler("set", new SetHandler(mapField, obj,
nameAttribute));
path.addHandler("map", new MapHandler(mapField, obj,
nameAttribute));
path.addHandler("ref", new RefHandler(mapField, obj,
nameAttribute));
}
public void .End(ElementPath path) {
path.removeHandler("value");
path.removeHandler("list");
path.removeHandler("set");
path.removeHandler("map");
path.removeHandler("ref");
}
}
|
private void setFieldValue(Object obj, Field field, String value) {
String fieldType = field.getType().getSimpleName();
try {
if (fieldType.equals("int"))
field.setInt(obj, new Integer(value));
else if (fieldType.equals("float"))
field.setFloat(obj, new Float(value));
else if (fieldType.equals("boolean"))
field.setBoolean(obj, new Boolean(value));
else if (fieldType.equals("char"))
field.setChar(obj, value.charAt(0));
else if (fieldType.equals("double"))
field.setDouble(obj, new Double(value));
else if (fieldType.equals("long"))
field.setLong(obj, new Long(value));
else
field.set(obj, value);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private void setFieldValue(Object obj, Field field, List<String> value) {
try {
field.set(obj, value);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
|
public static void main(String[] args) {
try {
BeanFactory factory = new BeanFactory();
factory.init("setting.xml");
Person p1 = (Person) factory.getBean("me");
System.out.print(p1.getName() + " ");
System.out.print(p1.getAge() + " ");
System.out.println(p1.getHeight());
Person p2 = (Person) factory.getBean("you");
System.out.print(p2.getName() + " ");
System.out.print(p2.getAge() + " ");
System.out.println(p2.getHeight());
ListOne list = (ListOne) factory.getBean("myList");
System.out.println(list.getMsg());
SetOne set = (SetOne) factory.getBean("mySet");
System.out.println(set.getMsg());
MapOne map = (MapOne) factory.getBean("myMap");
System.out.println(map.getMsg());
Persons us = (Persons) factory.getBean("us");
System.out.println(us.getI());
System.out.println(us.getU());
} catch (Exception e) {
e.printStackTrace();
}
}
|
Java代码实现依赖注入的更多相关文章
- 在ABAP里模拟实现Java Spring的依赖注入
Dependency Injection- 依赖注入,在Java Spring框架中有着广泛地应用.通过依赖注入,我们不必在应用代码里繁琐地初始化依赖的资源,非常方便. 那么ABAP能否从语言层面上也 ...
- Java Spring各种依赖注入注解的区别
Spring对于Bean的依赖注入,支持多种注解方式: @Resource javax.annotation JSR250 (Common Annotations for Java) @Inject ...
- JAVA框架 Spring 依赖注入
一:介绍 情景:我们在给程序分层的时候:web层.业务层.持久层,各个层之间会有依赖.比如说:业务层和持久层,业务层的代码在调用持久层的时候,传统方式:new 持久层类. 进而进行调用,这种方式会导致 ...
- 详解Java Spring各种依赖注入注解的区别
注解注入顾名思义就是通过注解来实现注入,Spring和注入相关的常见注解有Autowired.Resource.Qualifier.Service.Controller.Repository.Comp ...
- 【Java】 Spring依赖注入小试牛刀:编写第一个Spring ApplicationContext Demo
0 Spring的依赖注入大致是这样工作的: 将对象如何构造(ID是什么?是什么类型?给属性设置什么值?给构造函数传入什么值?)写入外部XML文件里.在调用者需要调用某个类时,不自行构造该类的对象, ...
- Effective Java —— 优先考虑依赖注入来引用资源
本文参考 本篇文章参考自<Effective Java>第三版第五条"Prefer dependency injection to hardwiring resources&qu ...
- [原创]20行ruby代码实现依赖注入框架
我需要依赖注入 业余时间开发的娱乐项目 (为了练习使用ruby语言) 遵循SRP原则,业务逻辑拆分由各个service类型提供,假设存在如下几个类型 GameService 封装主要游戏业务逻辑 Us ...
- Java反射及依赖注入简单模拟
一.编写Dao类 ? 1 2 3 4 5 6 7 8 9 10 11 package cn.com.songjy.annotation; import java.util.Date; publ ...
- [Android]使用Dagger 2进行依赖注入 - Producers(翻译)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/6234811.html 使用Dagger 2进行依赖注入 - P ...
随机推荐
- sqlserver主从复制
参考网站: http://www.178linux.com/9079 https://www.cnblogs.com/tatsuya/p/5025583.html windows系统环境进行主从复制操 ...
- leetcode496
public class Solution { public int[] NextGreaterElement(int[] findNums, int[] nums) { var list = new ...
- Nginx Windows 安装启动
原文连接:http://tengine.taobao.org/book/appendix_c.html#nginxwindows 下载 Nginx是开源软件,用户可以访问 http://nginx.o ...
- Spring boot Thymeleaf 配置
第一步:pom.xml加入依赖 <!-- HTML templates--> <dependency> <groupId>org.springframework.b ...
- as3 AIR 添加或删除ApplicationDirectory目录下文件
AIR的文件目录静态类型有五种: File.userDirectory //指向用户文件夹 File.documentsDirectory //指向用户文档文件夹 File.desktopDirect ...
- 4 并发编程-(进程)-守护进程&互斥锁
一.守护进程 主进程创建子进程,然后将该进程设置成守护自己的进程,守护进程就好比崇祯皇帝身边的老太监,崇祯皇帝已死老太监就跟着殉葬了. 关于守护进程需要强调两点: 其一:守护进程会在主进程代码执行结束 ...
- Others-接口集成方式
1. 异步通信方式可分为不互锁.半互锁和全互锁三种类型: a.不互锁方式 主模块发出请求信号后,不等待接到从模块的回答信号,而是经过一段时间.确认从模块已收到请求信号后,便撤消其请求信号:从设备接到请 ...
- ios 获得webview user-agent
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectZero]; NSString *myUserAgent = [webView s ...
- centos7 防火墙配置
firewall-cmd --zone=public --add-port=80/tcp --permanentfirewall-cmd --zone=public --add-port=8080/t ...
- Virtualbox [The headers for the current running kernel were not found] (操作过程后还是失败,显示相同问题)
在笔记本安装Ubuntu11.04增强功能失败 引用 fuliang@fuliang-VirtualBox:~$ sudo /etc/init.d/vboxadd setup Removing exi ...