我正在使用 Hibernate 在 Spring boot 中开发 REST API。
我的 Controller 里有这个功能
@PostMapping("/profile")
public ResponseEntity<String> saveProfile(@Valid @RequestBody SaveProfileVM saveProfileVM,
BindingResult bindingResult)
throws JsonProcessingException {
if (bindingResult.hasErrors()) return super.fieldExceptionResponse(bindingResult);
Profile profile;
boolean optimisticLockException = true;
int retryCount = 0;
do {
try {
profile = accountService.saveProfile(saveProfileVM.getAccountId(),
saveProfileVM.getName(),
saveProfileVM.getEmail());
optimisticLockException = false;
retryCount++;
} catch (ObjectOptimisticLockingFailureException exception) {
retryCount++;
System.out.println(exception.getMessage());
}
} while (optimisticLockException && retryCount < MAX_OPTIMISTIC_LOCK_EXCEPTION_RETRY_COUNT);
return ResponseEntity.status(HttpStatus.OK).body(objectMapper.writeValueAsString(profile));
}
MAX_OPTIMISTIC_LOCK_EXCEPTION_RETRY_COUNT
为 3
我不想在每个需要检查 ObjectOptimisticLockingFailureException
的方法中重复 do..while 和 try..catch block
do {
try{}
catch{}
} while()
有什么方法可以将 accountService.saveProfile()
传递给具有 do..while 和 try..catch block
的通用方法,以便我不必将 block 复制并粘贴到我需要的每个方法?
每个 Controller 都扩展一个 BaseController,所以在 BaseController 中包含通用方法可能会更好?
@RestController
@RequestMapping("/account")
public class AccountController extends BaseController {
你们能给个主意吗?
最佳答案
您可以使用 Spring 重试。更多 details
@Retryable(value = ObjectOptimisticLockingFailureException.class, maxAttempts = 3)
public void saveProfile(Long accountId, String name, String email){..}
关于spring-boot - 在 Controller 中传递服务的功能,以便不复制 try catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64853783/