【java】循环依赖

https://cloud.tencent.com/developer/article/1464430
java 循环依赖报错

新建3个service,然后互相引用

@Service
public class CarService {

    private RoadService roadService;
    private DriverService driverService;

    public CarService(RoadService roadService,DriverService driverService) {
        this.roadService = roadService;
        this.driverService = driverService;
    }

}

@Service
public class RoadService {

    private DriverService driverService;
    private CarService carService;

    public RoadService(DriverService driverService,CarService carService) {
        this.driverService = driverService;
        this.carService = carService;
    }

}

@Service
public class DriverService {

    private RoadService roadService;
    private CarService carService;

    public DriverService(RoadService roadService, CarService carService) {
        this.roadService = roadService;
        this.carService = carService;
    }

}


构建注入后会报错
解决方法有三

  1. 增加@Lazy注解
@Service
public class RoadService {

    private DriverService driverService;
    private CarService carService;

    public RoadService(@Lazy DriverService driverService,@Lazy CarService carService) {
        this.driverService = driverService;
        this.carService = carService;
    }

}
  1. 加上@Autowired注解
@Service
public class RoadService {

    @Autowired
    private DriverService driverService;
    @Autowired
    private CarService carService;

}
  1. 提出相关业务,不要用构造注入

你可能感兴趣的:(【java】循环依赖)