最近代碼中發(fā)現(xiàn),使用@ControllerAdvice注解過的controller,@Autowired注入的bean直接引用為null,見代碼中(3).
但是使用this的totring函數(shù)卻發(fā)現(xiàn)是有值的——代碼(1)部分,增加getter方法后,使用get方式也能獲取到(2)
原因未知,懷疑是@ControllerAdvice生成的代理訪問不了private對象,找到原因后更新
代碼
@ControllerAdvice
@ToString
@Data
public class HandleExceptionController {
private static final Logger LOG = LoggerFactory.getLogger(HandleExceptionController.class);
private VehicleBookConfig vehicleBookConfig;
private AccountService accountService;
@Autowired
public HandleExceptionController(VehicleBookConfig vehicleBookConfig, AccountService accountService) {
this.vehicleBookConfig = vehicleBookConfig;
this.accountService = accountService;
}
@ExceptionHandler
@ResponseBody
public final String handleAllException(Exception ex) {
LOG.error("exception", ex);
LOG.error("HandleExceptionController{}", this); // (1)
LOG.error("vehicleBookConfig{}", this.getVehicleBookConfig()); // (2)
LOG.error("accountService{}", accountService); // (3)
return "default exception";
}
}
結果

image.png