🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
Spring bean的创建,其本质上还是一个对象的创建,包含两部分:当前对象实例化和对象属性的实例化; ![](https://img.kancloud.cn/e3/15/e31505e7ff8e84e51c85f101267efd70_2066x714.png) 实现原理: ~~~ public class Appliction { public static void main(String[] args) throws InstantiationException, IllegalAccessException { BeanFactory beanFactory = new BeanFactory(); Object bean = beanFactory.getBean(ObjectA.class); System.err.println(bean); } } public class BeanFactory { private Map<String, Object> cacheMap = new HashMap<>(); public Object getBean(Class cla) throws IllegalAccessException, InstantiationException { String simpleName = cla.getSimpleName(); System.err.println(simpleName); if (cacheMap.containsKey(simpleName)) { return cacheMap.get(simpleName); } Object instance = cla.newInstance(); cacheMap.put(simpleName, instance); Field[] fields = cla.getDeclaredFields(); for (Field field : fields) { boolean present = field.isAnnotationPresent(AutoIoc.class); if (present) { Class<?> declaringClass = field.getType(); Object obj = getBean(declaringClass); field.setAccessible(true); field.set(instance, obj); } } return instance; } } public class ObjectA { @AutoIoc private ObjectB objectB; } public class ObjectB { @AutoIoc private ObjectA objectA; } @Retention(RetentionPolicy.RUNTIME) @Target(value = {ElementType.FIELD}) public @interface AutoIoc { } ~~~