-
修改后版本: 修改人: 修改日期: 2020/11/16 14:03 修改内容:
*/
@Component
public class B {
//@Autowired
A a;
public B() {
a = new A();
System.out.println(“B class is create”);
}
}
注册类A、B
package com.example.config;
import com.example.bean.B;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.bean.A;
/**
-
AppConfiguration
-
@author mazq
-
修改记录
-
修改后版本: 修改人: 修改日期: 2020/11/05 10:26 修改内容:
*/
@Configuration
public class AppConfiguration {
@Bean
public A a(){
return new A();
}
@Bean
public B b() {
return new B();
}
}
package com.example;
import com.example.config.AppConfiguration;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.example.bean.A;
/**
-
TestController
-
@author mazq
-
修改记录
-
修改后版本: 修改人: 修改日期: 2020/11/05 10:22 修改内容:
*/
public class TestApplication {
public static void testCircularReferences() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AppConfiguration.class);
//context.setAllowCircularReferences(false);
context.refresh();
A bean = context.getBean(A.class);
System.out.println(bean);
}
public static void main(String[] args) {
// 测试Sprin循环依赖
testCircularReferences();
}
}
经过测试,一直在循环调用:
4、循环依赖解决方法
==============
对于这种情况,Spring有处理方法?答案是有的,方法就是通过@Autowired注解,当然bean要是单例的,多例的情况不支持,原因后面分析
@Component
public class A {
@Autowired
B b;
public A() {
System.out.println(“A class is create”);
}
}
补充:除了@Autowired方法,我们还可以通过set方法处理循环依赖问题,当然也是仅支持单例bean,多例的情况不支持
5、关闭Spring循环依赖
==================
有个疑问