MethodValidationPostProcessor

MethodValidationPostProcessor

我试图将javax.validation.constraints.NotNull与org.springframework.validation.beanvalidation.MethodValidationPostProcessor.MethodValidationPostProcessor一起使用,但未在同一个类中按预期运行。拜托,你能告诉我为什么吗?

MethodValidationConfig类:

@Configuration
@ComponentScan({ "com.mypackage" })
public class MethodValidationConfig {

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

}


ValidationUtils类:

@Component
@Validated
@Slf4j
public class ValidationUtils {
    public void test1(@NotNull String[] test) {
        if(test == null) {
            log.error("Test is null!!!");
        }
    }

    public void test2() {
        test1(null);
    }

}


TestApplication类:

@EnableAsync
@EnableTransactionManagement
@SpringBootApplication
@Slf4j
public class TestApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(TestApplication.class, args);

        ValidationUtils validationUtils = context.getBean(ValidationUtils.class);

        try {
            validationUtils.test1(null);
        } catch (Exception e) {
            log.info("OK");
        }

        try {
            validationUtils.test2();
        } catch (Exception e) {
            log.info("OK");
        }

    }

}


com.mypackage.TestApplication:确定
com.mypackage.validationUtils:测试为空!

最佳答案

我假设发生了以下情况:当您调用test1()时,代理将拦截并进行验证。调用test2()时,它仅将调用委派给不涉及代理的真实对象。相似的问题:Spring AOP not working for method call inside another method

09-11 17:58