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>
Java代码实现依赖注入(2)
时间:2011-07-22 51cto博客 zhangjunhd
依据setting.xml,这里将构建两个Person类的实例me和you:
Person.java
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;}
}
紧接着,构建一个ListOne的实例myList:
ListOne.java
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;}
}
紧接着,构建一个SetOne的实例mySet:
SetOne.java
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;}
}
紧接着,构建一个MapOne的实例myMap:
MapOne.java
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;}
}
Java代码实现依赖注入(3)
时间:2011-07-22 51cto博客 zhangjunhd
最后构建一个Persons类的实例us,其中包含me和you两个已经构建好的对象:
Persons.java
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;}
}
主要的实现机制是(代码BeanFactory.java以及工程见附件),
1.通过一个HashMap保存构造好的对象,key就是bean的id属性,value就是这个对象;
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");
2.init方法读入配置文件setting.xml,并直接定位到beans下的bean元素,并实例化一个 ElementHandler对其处理。
public void init(String xmlUri) throws Exception {
SAXReader saxReader = new SAXReader();
File file = new File(xmlUri);
try {
saxReader.addHandler("/beans/be
|