image.png
package com.erik.spring;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ErikApplicationContext {
private Class aClass;
private ConcurrentMap<String, BeanDeinition> concurrentMap = new ConcurrentHashMap<>();
private ConcurrentMap<String, Object> concurrentSingleMap = new ConcurrentHashMap<>();
public ErikApplicationContext(Class aClass) throws IOException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
this.aClass = aClass;
// 扫描
if (aClass.isAnnotationPresent(ComponentScan.class)) {
ClassLoader loader = aClass.getClassLoader();
ComponentScan annotation = (ComponentScan) aClass.getAnnotation(ComponentScan.class);
String value = annotation.value();
String replace = value.replace(".", "/");
URL resource = loader.getResource(replace);
File file = new File(resource.getFile());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File file1 : files) {
if (file1.getName().endsWith(".class")) {
String s = file1.getName().replace(".class", "");
String newV = value + "." + s;
System.out.println(newV);
Class<?> loadClass = loader.loadClass(newV);
// 判断是否含有Component注解
if (loadClass.isAnnotationPresent(Component.class)) {
Component component = loadClass.getAnnotation(Component.class);
String value1 = component.value();
BeanDeinition deinition = new BeanDeinition();
String scope = "";
if (loadClass.isAnnotationPresent(Scope.class)) {
scope = loadClass.getAnnotation(Scope.class).value();
}else {
scope = "singleton";
}
deinition.setScope(scope);
deinition.setType(loadClass);
concurrentMap.put(value1, deinition);
}
}
}
}
}
// 获取所有的单例对象,封装起来
for (String s : concurrentMap.keySet()) {
BeanDeinition deinition = concurrentMap.get(s);
if (deinition.getScope().equals("singleton")) {
if (concurrentSingleMap.get(s) == null) {
Object bena = createBena(s, deinition);
concurrentSingleMap.put(s, bena);
}
}
}
}
private Object createBena(String beanName, BeanDeinition beanDeinition) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class type = beanDeinition.getType();
return type.getConstructor().newInstance();
}
public Object getBean(String beanName) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
BeanDeinition o = concurrentMap.get(beanName);
if (o == null) {
throw new NullPointerException();
}
if (o.getScope().equals("singleton")) {
return concurrentSingleMap.get(beanName);
}
// 创建
return createBena(beanName, o);
}
}