Github address: github.com/zexho994/IO…

Resolving circular dependencies

Use “level 3 caching” in Spring to solve the problem of loop dependency. Don’t worry about why Spring uses 3 maps to implement the problem. Forget the details of the implementation and start with the cause of the problem.

What is circular dependency?

The following A and B depend on each other, so there is A problem of creating B when creating A, but creating A when creating B, which seems to be A chicken-and-egg problem.

@Bean
public class ClassA {
    @Autowired
    public ClassB ib;

}

@Bean
public class ClassB {
    @Autowired
    public ClassA ia;
    
}
Copy the code

But it makes sense to know that Bean creation is actually a multi-step process.

Graph LR n0(start) --> n1(create instance) --> n2(fill fields that need to be injected) --> n3(end)

Instance a = ClassA; instance B = b.ib = null; Then assign a.ib = b and b.ia = a, after which the fields in A and B are all assigned and are fully usable objects.

public Object getBean(String beanName) {
    BeanDefinition bean = this.getBeanInstance(beanName);
    if(! bean.isInit()) {try {
            this.initBean(bean);
        } catch(IllegalAccessException e) { e.printStackTrace(); }}return bean.getInstance();
}

// Initialize the bean
private void initBean(BeanDefinition beanDefinition) throws IllegalAccessException {
    Object instance = beanDefinition.getInstance(); // Obtain the isntance of the bean
    beanDefinition.setStatusInitialized();  // Set to initialized
    this.initAutowire(instance);
}

// Iterate over all fields and inject for implementations with @AuthWired annotations
private void initAutowire(Object instance) throws IllegalAccessException {
    Field[] fields = instance.getClass().getFields();
    for (Field field : fields) {
        if (field.getDeclaredAnnotationsByType(Autowired.class).length == 0) {
            continue; } Class<? > fieldType = field.getType(); Object bean =this.getBean(fieldType.getSimpleName());
        field.set(instance, bean);  / / field assignment}}Copy the code

A good analogy is leetcode’s algorithm two sum leetcode-cn.com/problems/tw… , one of the solutions is to traverse one side, store all the values and indexes into the map, and then traverse the map once, each time determining whether there is the desired number.

For instance, put it in the map, and then fill in all of the fields in the map.