0

I tried to use javax.validation.constraints.NotNull with org.springframework.validation.beanvalidation.MethodValidationPostProcessor.MethodValidationPostProcessor but does not run as expected inside the same class. Please, could you tell me why ?

MethodValidationConfig class:

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

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

}

ValidationUtils class:

@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 class:

@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 : OK com.mypackage.validationUtils : Test is null!!

MC Emperor
  • 22,334
  • 15
  • 80
  • 130

1 Answers1

2

I assume the following happens: when you call test1(), the proxy intercepts, and does the validation. When you call test2(), it simply delegates the call to the real object, where there is no proxy involved. Similar problem: Spring AOP not working for method call inside another method