如何使用方法级验证

时间:2019-07-12 11:57:12

标签: spring validation

我正在尝试使用javax.validation验证方法中使用的一些参数,但是我在正确执行操作时遇到了麻烦。

这是我的方法:

ServiceResponseInterface getEngineTriage(
            @NotNull(message = Constants.MANDATORY_PARAMETERS_MISSING) String riskAssessmentId,
            @NotNull(message = Constants.MANDATORY_PARAMETERS_MISSING) String participantId,
            @Pattern(regexp = "NEW|RENEWAL|EDIT|OPERATION|RATING", flags = Pattern.Flag.CASE_INSENSITIVE, message = Constants.WRONG_PARAMETERS) String eventType) {

                ~Some code~ 
                return ServiceResponseNoContent.ServiceResponseNoContentBuilder.build();
            }

该类具有@Validated批注,这时我被卡住了,如何在调用该方法时检查是否验证了对方法?

1 个答案:

答案 0 :(得分:1)

基本上,如果您的配置正确,那么如果发生任何验证错误,则不会执行您的方法。因此,您需要使用一个简单的try-catch块来处理您的方法。

我将在下面的Spring中提供用于方法级别验证的示例配置。

public interface IValidationService {

    public boolean methodLevelValidation(@NotNull String param);

}
@Service
@Validated
public class ValidationService implements IValidationService {

    @Override
    public boolean methodLevelValidation(String param) {
        // some business logic here
        return true;
    }

}

您可以处理以下任何验证错误:

@Test
public void testMethodLevelValidationNotPassAndHandle() {

    boolean result = false;
    try {
        result = validationService.methodLevelValidation(null);
        Assert.assertTrue(result);
    } catch (ConstraintViolationException e) {
        Assert.assertFalse(result);
        Assert.assertNotNull(e.getMessage());
        logger.info(e.getMessage());
    }

}

注意:如果您已从一个组件中实现了组件,则需要在界面中定义验证批注。否则,您可以将其放在裸机组件中:

@Component
@Validated
public class BareValidationService {

    public boolean methodLevelValidation(@NotNull String param) {

        return true;
    }

}

希望这会有所帮助,加油!

相关问题