packagecom.sinoair.gtms.controller.web.IOC;importjavax.annotation.Resource;importjavax.xml.ws.Service;importjava.lang.reflect.Field;importjava.util.HashMap;importjava.util.List;importjava.util.Map;public classMyIOC {/**
*模拟Spring扫描的注解包
*/private final staticStringpackageName="com.albert.AnnotationTest";/**
*存放注解的bean对象
*/private staticMapbeanMap=newHashMap();static{try{
packageToScan();
}catch(InstantiationExceptione) {
e.printStackTrace();
}catch(IllegalAccessExceptione) {
e.printStackTrace();
}
}/**
*根据beanName从容器获取bean对象
* @parambeanName* @return*/public staticObject getBean(String beanName){
Object obj =null;
obj =beanMap.get(beanName);returnobj;
}/**
*遍历包中的注解类
* @throwsIllegalAccessException
* @throwsInstantiationException
*/private static voidpackageToScan()throwsInstantiationException,IllegalAccessException{
List clsList =ClassByPackage.getClasssFromPackage(packageName);//先加载daofor(Class cls : clsList){//判断类是不是有@Respository注解if(cls.isAnnotationPresent(Respository.class)){
String clsName =AlbertUtil.getBeanName(cls.getName());//bean对象存入mapbeanMap.put(clsName,cls.newInstance());
}
}//加载service,同时对其中@Resource注解的属性进行赋值for(Class cls : clsList){if(cls.isAnnotationPresent(Service.class)){
String clsName =cls.getName();
clsName =clsName.substring(clsName.lastIndexOf(".")+1, clsName.length());beanMap.put(AlbertUtil.toLowerCaseFirstOne(clsName),cls.newInstance());//扫描注解@Resource的属性并赋值Field[] field = cls.getDeclaredFields();for(Field f : field){//判断属性是不是有@Resource注解if(f.isAnnotationPresent(Resource.class)){
f.setAccessible(true);
f.set(beanMap.get(AlbertUtil.getBeanName(cls.getName())),beanMap.get(f.getName()));
}
}
}
}
}
}