在springboot中遇到了UnsatisfiedDependencyException: Error creating bean with name 'XXXController'的问题,代码如下
//controller
public class XXXController{
@Autowired
private XXXService xxxService;
......
}
//service
public class XXXService{
@Autowired
private Constant constant;
private String ip = constant.getIp();
public void test(){
......
}
}
询问某大佬之后,得知报错的原因是因为:在将service注入ioc容器的时候,需要初始化service,因为service里面又注入了constant,当springboot发现ioc容器里没有constant的bean时,会先去初始化constant。关键是,它不会马上去初始化constant,而是先放上一个占位符,然后进行接下来的初始化操作。接下又需要初始化ip,结果ip引用了constant,因此会报错。
解决方法:
//controller
public class XXXController{
@Autowired
private XXXService xxxService;
......
}
//service
public class XXXService{
@Autowired
private Constant constant;
private String ip = null;
public void test(){
ip = constant.getIp();
......
}
}