暂时支持8种基本数据类型,String类型,引用类型,List的注入。
核心代码
package day01;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
/**
* 模拟 IOC+DI
* @author fh
*@date 下午7:26:50
*/
public class springIOCTest {
//存入所有一级对象+类名
public static Map<String, Object> map = new HashMap<String, Object>();
//存入注入对象与其需要注入对象名称
public Map<Class<?>, String> map2 = new HashMap<Class<?>, String>();
public static void main(String[] args) throws Exception {
springIOCTest st = new springIOCTest();
st.xmlParse();
for (Object string : st.map.values()) {
//System.out.println(string);
}
// for (Entry<Class<?>, String> enrty :st.map2.entrySet() ) {
// Class<?> class1 = enrty.getKey();
// class1.getDeclaredField(enrty.getValue());
// }
}
/**
* dom解析
* @throws DocumentException
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws Exception
*/
public void xmlParse() throws DocumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
SAXReader sr=new SAXReader();
Document document=sr.read("D:\eclipseworkspace\Briup-SpringStudy\test.xml");
//根目录
Element root = document.getRootElement();
List<Element> elements = root.elements();
//所有一级节点
for (Element element : elements) {
String id = element.attributeValue("id");
String parkagename = element.attributeValue("class");
Class<?> class1 = Class.forName(parkagename);
Object Instance = class1.newInstance();
//保存到map集合
map.put(id, Instance);
List<Element> elements2 = element.elements();
if (elements2.size() > 0) {
//所有二级节点
for (Element element2 : elements2) {
String refname = element2.attributeValue("name");
String value = element2.attributeValue("value");
Field field1 = null;
String ref = element2.attributeValue("ref");
//缺陷:注入对象必须在被注入对象之前
if (value==null&&ref!=null) {
//引用对象类型
field1 = class1.getDeclaredField(refname);
basicType(true,Modifier.isPrivate(field1.getModifiers()), class1, Instance, field1, ref, refname);
}else if (ref==null&&value!=null) {
//String类型或者基本类型
field1 = class1.getDeclaredField(refname);
basicType(false,Modifier.isPrivate(field1.getModifiers()), class1, Instance, field1, value, refname);
}else {
//是否有三级节点
List<Element> elements3 = element2.elements();
if (elements3.size()>0) {
Element e = (Element) element2.elements().get(0);
String name = e.getName();
if ("list".equals(name)) {
ListType(class1,Instance,element2);
}else if ("array".equals(name)) {
}else if ("map".equals(name)) {
}else if ("set".equals(name)) {
}else {
throw new RuntimeException(name+" is not defined");
}
}
}
//方法二:先保存依赖关系,最后注入
//map2.put(class1, refname);
}
}
}
}
private <T> void ListType(Class<T> c,Object instance, Element elements2) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
String Typename = elements2.attributeValue("name");
//Class<?> forName = Class.forName(Typename);
List<Element> elements = elements2.elements();
Element e = (Element) elements2.elements().get(0);
List<Element> elements3 = e.elements();
String fieldname = e.getName();
//System.out.println(fieldname);
Field field = c.getDeclaredField(Typename);
ArrayList al = new ArrayList();
for (Element element :elements3) {
//System.out.println(element.getName());
String text = element.getText();
al.add(text);
}
field.setAccessible(true);
field.set(instance, al);
}
/**
* 注入方式判断,注入类型判断
* @param isQuoteType
* @param b
* @param class1
* @param Instance
* @param field1
* @param value
* @param refname
* @throws NoSuchMethodException
* @throws SecurityException
* @throws NumberFormatException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public static <T> void basicType(boolean isQuoteType,boolean b,Class<T> class1,Object Instance,Field field1,String value,String refname) throws NoSuchMethodException, SecurityException, NumberFormatException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Method method = null;
//是否为private ,若为private必须通过set,get方法访问
if(b){
//方法二:通过set方法注入
if (isQuoteType) {
//引用类型
method = class1.getMethod("set"+Character.toUpperCase(refname.charAt(0))+refname.substring(1, refname.length()), map.get(value).getClass());
}else{
//基本类型+String
method = class1.getMethod("set"+Character.toUpperCase(refname.charAt(0))+refname.substring(1, refname.length()), field1.getType());
}
MethodTypeHander(field1,method,Instance,value);
}else{
//方法一:属性直接注入
FieldTypeHander(field1,Instance,value);
}
}
/**
* 属性直接注入
* @param field
* @param Instance
* @param value
* @throws NumberFormatException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public static void FieldTypeHander(Field field,Object Instance,String value) throws NumberFormatException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// System.out.println("FieldTypeHander "+field.getType());
//设置能否访问,不然private,protected属性会被阻止,破坏封装
field.setAccessible(true);
if ("byte".equals(field.getType().toString())) {
field.setByte(Instance, Byte.parseByte(value));
}else if ("short".equals(field.getType().toString())) {
field.setShort(Instance, Short.parseShort(value));
}else if ("int".equals(field.getType().toString())) {
field.setInt(Instance, Integer.parseInt(value));
}else if ("long".equals(field.getType().toString())) {
field.setLong(Instance, Long.parseLong(value));
}else if ("double".equals(field.getType().toString())) {
field.setDouble(Instance, Double.parseDouble(value));
}else if ("float".equals(field.getType().toString())) {
field.setFloat(Instance, Float.parseFloat(value));
}else if ("class java.lang.String".equals(field.getType().toString())) {
field.set(Instance,value);
}else if ("boolean".equals(field.getType().toString())) {
field.setBoolean(Instance,Boolean.parseBoolean(value));
}else {
field.set(Instance, map.get(value));
}
}
/**
* 通过方法注入
* @param field
* @param method
* @param Instance
* @param value
* @throws NumberFormatException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public static void MethodTypeHander(Field field,Method method,Object Instance,String value) throws NumberFormatException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//System.out.println("MethodTypeHander "+field.getType());
if ("byte".equals(field.getType().toString())) {
method.invoke(Instance, Byte.parseByte(value));
}else if ("short".equals(field.getType().toString())) {
method.invoke(Instance, Short.parseShort(value));
}else if ("int".equals(field.getType().toString())) {
method.invoke(Instance, Integer.parseInt(value));
}else if ("long".equals(field.getType().toString())) {
method.invoke(Instance, Long.parseLong(value));
}else if ("double".equals(field.getType().toString())) {
method.invoke(Instance, Double.parseDouble(value));
}else if ("float".equals(field.getType().toString())) {
method.invoke(Instance, Float.parseFloat(value));
}else if ("class java.lang.String".equals(field.getType().toString())) {
method.invoke(Instance,value);
}else if ("boolean".equals(field.getType().toString())) {
method.invoke(Instance,Boolean.parseBoolean(value));
}else {
method.invoke(Instance, map.get(value));
}
}
}
xml文件
test.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:u="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean id="Address" class="day01.bean.Address">
<property name="city" value="南昌"/>
<property name="street" value="双港东大街"/>
<property name="country" value="中国"/>
</bean>
<bean id="Person" class="day01.bean.Person">
<property name="sNo" value="1"/>
<property name="name" value="fh"/>
<property name="gender" value="true"/>
<property name="age" value="21"/>
<property name="arraytest">
<list value-type="int">
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
<property name="address" ref="Address"/>
</bean>
<bean id="UserDAO" class="day01.dao.UserDAO"/>
<bean id="UserService" class="day01.service.UserService">
<property name="userDAO" ref="UserDAO"/>
</bean>
</beans>
结果: