springboot 循环依赖示例
************************
循环依赖解决
尽量不要使用循环依赖;
当无可避免要使用循环依赖时,禁止使用构造器注入依赖属性,使用注解(@Resource、@Autowired)属性
************************
自循环依赖:属性注入
****************
pojo 层
Person
@Component
public class Person {
@Resource
private Person person;
public void print(){
System.out.println(this.person);
}
}
****************
controller 层
HelloController
@RestController
public class HelloController {
@Resource
private Person person;
@RequestMapping("/hello")
public String hello(){
person.print();
return "success";
}
}
****************
控制台输出
2020-07-03 18:20:11.260 INFO 13544 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-07-03 18:20:11.266 INFO 13544 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 6 ms
com.example.demo.pojo.Person@2b26c8e4
使用三级缓存,解决了属性注入自循环依赖
************************
自循环依赖:构造器注入
****************
pojo 层
Person
@Component
public class Person {
private Person person;
public Person(Person person){
this.person=person;
}
public void print(){
System.out.println(this.person);
}
}
****************
controller 层
HelloController
@RestController
public class HelloController {
@Resource
private Person person;
@RequestMapping("/hello")
public String hello(){
person.print();
return "success";
}
}
****************
控制台输出
2020-07-03 18:24:33.550 INFO 19416 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-07-03 18:24:33.668 INFO 19416 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-07-03 18:24:33.674 ERROR 19416 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
helloController
┌─────┐
| person defined in file [E:\java\IdeaProjects\springboot 测试\target\classes\com\example\demo\pojo\Person.class]
└─────┘
启动报错:存在自循环依赖,使用构造器创建person,person没有添加到缓存,不能提前暴露
************************
自循环依赖:代理对象(@Transactional)
****************
service 层
HelloService
public interface HelloService {
void hello();
}
****************
serviceImpl 层
HelloServiceImpl
@Service
public class HelloServiceImpl implements HelloService {
@Resource
private HelloService helloService;
@Override
@Transactional
public void hello() {
System.out.println(helloService);
System.out.println("hello world");
}
}
****************
controller 层
HelloController
@RestController
public class HelloController {
@Resource
private HelloService helloService;
@RequestMapping("/hello")
public String hello(){
helloService.hello();
return "success";
}
}
****************
控制台输出
localhost:8080/hello