经典面试题:
面试官经常会问:Spring的两个Bean可以循环依赖吗?
答:Spring默认单例支持循环依赖
实例证明
我们首先在一个Spring项目里面准备两个Bean,让它们互相依赖注入:
@Component
public class IndexService {
@Autowired
private UserService userService;
public IndexService() {
System.out.println("from IndexService");
}
public void getUserService() {
userService.getIndexService();
}
}
@Component
public class UserService {
@Autowired
private IndexService indexService;
public UserService() {
System.out.println("from UserService");
}
public void getIndexService() {
System.out.println("indexService:"+indexService);
}
}
然后如图创建一个配置类,用来扫描Bean
@ComponentScan("com.zyc")
public class AppConfig {
}
最后创建一个Test类:
public class Test {
public static void main(String[] args) {
//初始化Spring容器
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
//获取Bean及其方法
ac.getBean(IndexService.class).getUserService();
}
}
查看控制台输出:
总结
Spring容器初始化时,通过配置类扫描到这两个Bean,完成其依赖注入,触发了它们的构造器方法,打印日志。
然后通过getBean获取IndexService执行getUserService()方法,该方法调用了UserService,并调用其getIndexService()方法,这个方法反过来又调用了IndexService。输出日志正确,所以它们是循环依赖的。