1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| public class AnnotationApplicationContext implements ApplicationContext {
private Map<Class<?>, Object> beanFactory = new HashMap<>(); private static String rootPath;
@Override public Object getBean(Class<?> clazz) { return beanFactory.get(clazz); }
public AnnotationApplicationContext(String basePackage) { String packagePath = basePackage.replaceAll("\\.", "\\\\"); Enumeration<URL> urls; try { urls = Thread.currentThread().getContextClassLoader().getResources(packagePath); } catch (IOException e) { throw new RuntimeException(e); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); String filePath = URLDecoder.decode(url.getFile(), StandardCharsets.UTF_8); rootPath = filePath.substring(0, filePath.length() - packagePath.length()); loadBean(new File(filePath)); loadDI(); } }
private void loadBean(File file) { if (!file.isDirectory()) return; File[] childrenFiles = file.listFiles(); if (childrenFiles == null) return; for (File childrenFile : childrenFiles) { if (childrenFile.isDirectory()) loadBean(childrenFile); else { String pathWithClass = childrenFile.getAbsolutePath().substring(rootPath.length() - 1); if (!pathWithClass.contains(".class")) return; String allName = pathWithClass.replaceAll("\\\\", ".").replace(".class", ""); try { instanceClass(allName); } catch (Exception e) { throw new RuntimeException(e); } } } }
private void instanceClass(String allName) throws Exception { Class<?> clazz = Class.forName(allName); if (clazz.isInterface()) return; Bean annotation = clazz.getAnnotation(Bean.class); if (annotation == null) return; Object instance = clazz.getConstructor().newInstance(); beanFactory.put(clazz.getInterfaces().length > 0 ? clazz.getInterfaces()[0] : clazz, instance); }
private void loadDI(){ Set<Map.Entry<Class<?>, Object>> entries = beanFactory.entrySet(); for (Map.Entry<Class<?>, Object> entry : entries) { Object value = entry.getValue(); Class<?> clazz = value.getClass(); Field[] declaredFields = clazz.getDeclaredFields(); for (Field declaredField : declaredFields) { DI annotation = declaredField.getAnnotation(DI.class); if (annotation==null) return; declaredField.setAccessible(true); try { declaredField.set(value,beanFactory.get(declaredField.getType())); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } } }
|