Spring Data
的Repository
可以返回null
這是意想不到的我,所以我用這樣的AOP:這是一個好的做法是使用AOP避免庫空返回
@Around("execution(* com.example.demo.repository.*.findOne(..))")
public Object aroundRepository(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
Object ret = pjp.proceed(args);
if (ret == null) throw new NullEntityException("null");
return ret;
}
其中NullEntityException
是一個自定義異常將在這裏處理:
@ControllerAdvice
public class CustomControllerAdvice {
@ExceptionHandler({NullEntityException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
ErrorMessage handleCustomException(Exception e) {
return new ErrorMessage(e.getMessage());
}
}
我的項目中的控制器都是@RestController
。那麼,是否在我的DAO層中防止所有findOne
方法返回null,並且沒有if (entity == null) throw new NullEntityException("null")
樣板文件?
感謝您的回答和命名建議! – zl2003cn