在控制器中传递服务的功能以不复制 try catch 块

kis*_*Tae 2 lambda hibernate controller function spring-boot

我正在使用 Hibernate 在 Spring Boot 中开发 REST API。

我的控制器中有这个功能

@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));
} 
Run Code Online (Sandbox Code Playgroud)

并且MAX_OPTIMISTIC_LOCK_EXCEPTION_RETRY_COUNT是 3

我不想do..while and try..catch blocks在需要检查的每个方法中复制ObjectOptimisticLockingFailureException

do { 
   try{} 
   catch{} 
} while()
Run Code Online (Sandbox Code Playgroud)

有什么方法可以传递accountService.saveProfile()给具有 的通用方法,do..while and try..catch block以便我不必将块复制并粘贴到我需要的每个方法中?

每个控制器都扩展了一个 BaseController 所以,在 BaseController 中拥有通用方法可能会很好?

@RestController
@RequestMapping("/account")
public class AccountController extends BaseController {
Run Code Online (Sandbox Code Playgroud)

各位大侠能给个思路吗?

use*_*814 6

您可以使用弹簧重试。更多的details

@Retryable(value = ObjectOptimisticLockingFailureException.class, maxAttempts = 3)
public void saveProfile(Long accountId, String name, String email){..}
Run Code Online (Sandbox Code Playgroud)