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 ...
随机推荐
- WebService客户端调用的几种方式
1.用组件HTTPRIO,支持VCL WIN32和FIRE MONKEY跨平台Android手机 HTTPRIO1.URL := 'http://127.0.0.1:8080/soap/IsoapTe ...
- 基于OpenGL编写一个简易的2D渲染框架-10 重构渲染器-Pass
Pass,渲染通路,一个渲染通路指的是一次像素处理和一次顶点处理,也就是指的是一次绘制.简单来说就是顶点数据在渲染管线中走一遍最后绘制. 渲染粒子系统的粒子时,需要开启 OpenGL 的混合模式,并使 ...
- 5 python 内置类
1.实例属性和类属性 给实例绑定属性的方法是通过实例变量,或者通过self变量: class Chinese: def __init__(self,name,sex,age): self.name = ...
- UI5-文档-4.13-Margins and Paddings
我们的应用程序内容仍然粘在信箱的角落里.要微调布局,可以向上一步添加的控件添加空白和填充. 我们将使用SAPUI5提供的标准类,而不是手工向控件添加CSS.这些类负责一致的分级步骤.从左到右的支持和响 ...
- WP runtime 获取cookie
HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter(); HttpCookieManager http ...
- ccttp图片处理过程
1.python输出404的图片 #!/usr/bin/python # coding: utf-8 import psycopg2 import sys from datetime import * ...
- Mybatis知识(4)
1.当实体类中的属性名和表中的字段名不一样 解决办法①: 通过在查询的sql语句中定义字段名的别名,让字段名的别名和实体类的属性名一致 <select id=”selectorder” para ...
- 通过beego快速创建一个Restful风格API项目及API文档自动化(转)
通过beego快速创建一个Restful风格API项目及API文档自动化 本文演示如何快速(一分钟内,不写一行代码)的根据数据库及表创建一个Restful风格的API项目,及提供便于在线测试API的界 ...
- Python基础杂点
Black Hat Python Python Programming for Hackers and Pentesters by Justin Seitz December 2014, 192 p ...
- TEXT 3 Food firms and fat-fighters
TEXT 3 Food firms and fat-fighters 食品公司与减肥斗士 Feb 9th 2006 From The Economist Global Agenda Five lead ...