AnnotationConfigApplicationContext
bootstrap jre/lib
Ext jre/ext/lib
App classpath
package com.zw.spring;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class ZwAnnotationConfigApplicationContext {
static private Map<String,Object> beanMap;
static {
beanMap=new HashMap<>();
}
private Class configClass;
public ZwAnnotationConfigApplicationContext(Class configClass)throws Exception {
this.configClass = configClass;
//获取配置类的Scan注解
ComponentScan componentScan = (ComponentScan)this.configClass.getDeclaredAnnotation(ComponentScan.class);
//获取注解参数值,以获取需要扫描包的路径
String path = componentScan.value();
//把com.zw.service替换成com/zw/service
String replace = path.replace(".", "/");
//利用路径获取类文件的物理全路径
ClassLoader classLoader = ZwAnnotationConfigApplicationContext.class.getClassLoader();
URL resource = classLoader.getResource(replace);
//生成该路径对应的file文件
String file = resource.getFile();
File file1 = new File(file);
//判读是否是文件夹,如果是文件夹进行全文件夹扫描,如果不是文件夹的就直接判断加载类
if (file1.isDirectory()){
//获取该文件夹下面的所有的文件
File[] files = file1.listFiles();
for (File f : files) {
if(f.getName().endsWith(".class")){
//获取该文件的全路径
String absolutePath = f.getAbsolutePath();
//截取包相关的字段 com\zw\service\UserService
String com = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
//转化为包名的格式com.zw.service.UserService
String replace1 = com.replace("\\", ".");
//加载类对象
Class aClass = classLoader.loadClass(replace1);
//获取判断类是否有spring标记的注解,如果有则进入逻辑
if (aClass.isAnnotationPresent(Component.class)){
//获取注解
Component comAnnotation = (Component)aClass.getDeclaredAnnotation(Component.class);
//获取类构造器
Constructor declaredConstructor = aClass.getDeclaredConstructor();
//创造一个单例对象,把注解中获取的对象名称与对象一键值对的方式保存起来
Object o = declaredConstructor.newInstance();
System.out.println(o.hashCode());
beanMap.put(comAnnotation.value(),o);
}
}
}
}else {
if ( file1.getName().endsWith(".class")){
String absolutePath = file1.getAbsolutePath();
String com = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
String replace1 = com.replace("\\", ".");
Class aClass = classLoader.loadClass(replace1);
if(aClass.isAnnotationPresent(Component.class)){
Component component = (Component)aClass.getAnnotation(Component.class);
Constructor declaredConstructor = aClass.getDeclaredConstructor();
Object o = declaredConstructor.newInstance();
beanMap.put(component.value(),o);
}
}
}
}
public Object getBean(String beanName){
//根据提供的对象名称获取对象返回
return beanMap.get(beanName);
}
}