关于Spring的依赖注入以及Bean的实例化过程,在Spring自动注入源码分析和Spring-IOC之实例化Bean源码及生命周期分析这俩篇文章已经讲的很清楚了。这里就不重复介绍了,主要来分析下Spring循环依赖问题。
@Configuration
@ComponentScan("com.su.spring.populate")
public class PopulateConfig {
}
@Service
public class UserService {
@Autowired
UserDao userDao;
}
@Repository
public class UserDao {
@Autowired
UserService userService;
}
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(PopulateConfig.class);
}
}
总结:spring先将x对象实例化出来,并且先将这个x对象放到singletonFactories这个Map中。接下来尝试注入属性y对象,由于y对象还没创建出来,接着进行y对象的实例化过程。同样的,先将y对象实例化出来,并且先将这个y对象放到singletonFactories这个Map中。接下来尝试注入属性x对象,这时候可以从singletonFactories中拿到x对象后完成属性注入。这样,完整的y对象已经实例化出来了,顺着方法调用链回去,接下来会完成x对象属性y对象的注入,这样,完成的x对象也实例化出来了。