手搓Spring Ioc ?

"成为J佬的一天"

Posted by HZY on December 13, 2025

写在前面

本章节起始于研究java核心技术卷,不知不觉发现已经有很多特性能够支持自己去进行一些创造,比如说,我可以实现Ioc整个流程,这便是反射的用武之地 再比如说。。。

手撕SpringIoc容器

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
public class BeanContainer {

    private final Map<Class<?>, Object> singletons = new HashMap<>();
    private final Set<Class<?>> creating = new HashSet<>();

    public <T> T getBean(Class<T> type) {
        if (singletons.containsKey(type)) {
            return type.cast(singletons.get(type));
        }

        if (creating.contains(type)) {
            throw new IllegalStateException("Circular dependency: " + type);
        }

        creating.add(type);
        try {
            T instance = createBean(type);
            singletons.put(type, instance);
            return instance;
        } finally {
            creating.remove(type);
        }
    }

    private <T> T createBean(Class<T> type) {
        try {
            Constructor<?> ctor = selectConstructor(type);
            Object[] deps = resolveDependencies(ctor);
            ctor.setAccessible(true);
            return type.cast(ctor.newInstance(deps));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Constructor<?> selectConstructor(Class<?> type) {
        Constructor<?>[] ctors = type.getDeclaredConstructors();
        if (ctors.length != 1) {
            throw new IllegalStateException("Only single constructor supported: " + type);
        }
        return ctors[0];
    }

    private Object[] resolveDependencies(Constructor<?> ctor) {
        Parameter[] params = ctor.getParameters();
        Object[] deps = new Object[params.length];
        for (int i = 0; i < params.length; i++) {
            deps[i] = getBean(params[i].getType());
        }
        return deps;
    }
}

手搓@UUID注解

implements BeanPostProcessor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class UUIDBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        //拿到bean,得到class,
        if (bean instanceof BeanPostProcessor) {
            return bean;
        }
        Class cl = bean.getClass();
        Field[] fields = cl.getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(UUID.class)) {
                f.setAccessible(true);
                try {
                    f.set(bean, java.util.UUID.randomUUID().toString());
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return bean;
    }
}