1.先来看一个循环依赖的demo
@Service
public class TestService1 {
@Autowired
private TestService2 testService2;
@Async
public void meth1() {
System.out.println("testService2-meth1");
testService2.meth2();
}
public void meth2() {
System.out.println("testService2-meth2");
}
}
@Service
public class TestService2 {
@Autowired
private TestService1 testService1;
public void meth1() {
System.out.println("TestService1-meth1");
testService1.meth2();
}
public void meth2() {
System.out.println("TestService1-meth2");
}
}
public class BeanApplication {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
//User user = context.getBean(User.class);
//user.sayHi();
TestService1 testService1 = context.getBean(TestService1.class);
testService1.meth1();
}
}
运行结果:
循环依赖正确执行了,那spring是如何做的呢?如下面
2.用一级缓存可以解决循环依赖吗?
3.用二级缓存可以解决循环依赖吗?
可以,但无法解决AOP动态代理问题
3.用三级缓存完美解决
三级缓存解决二级缓存动态代理问题