Kim
Kim

Reputation: 5425

How to validate parameters of methods that calling from same class?

Validation works as expected for bean class method calling from "@Autowired" parent. But how to validate inner method if it is called from the class itself?

@Bean
@Validated
public class TestBean {

    public void testMethod(@NotNull String param1) {
        System.out.println("here at TestBean.test");
        this.innerMethod(null);
    }

    private void innerMethod(@NotNull String param1) {
        System.out.println("here at TestBean.innerMethod");
    }
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class TestBeanTest {

    @Autowired
    private TestBean bean;

    @Test
    public void testMethod() {
        bean.testMethod(null); // -> error as expected
        bean.testMethod("example"); // -> there are no ConstraintValidation error in "inner method", how to validate "innerMethod"?
    }
}

Upvotes: 1

Views: 755

Answers (1)

Anish B.
Anish B.

Reputation: 16459

Spring doesn't valid the data when parameters are passed from a method which is being called from another method.

The better approach is to put condition to validate the data before sending it.

The updated code will be :

@Bean
@Validated
public class TestBean {

    @Autowired
    private Service Service;

    public void testMethod(@NotNull String param1) {
        System.out.println("here at TestBean.test");
        // let's say some call.
        String arbitrary = service.getSomeStringData(param1);
        // validate it before sending it.
        if(arbitrary != null) {
           this.innerMethod(arbitrary);
        }        
    }

    private void innerMethod(String param1) {
        System.out.println("here at TestBean.innerMethod");
    }
}

Upvotes: 1

Related Questions