首页 > 解决方案 > 如何验证从同一类调用的方法的参数?

问题描述

对于从“@Autowired”父级调用的 bean 类方法,验证按预期工作。但是如果从类本身调用内部方法,如何验证它呢?

@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"?
    }
}

标签: javaspringspring-boot

解决方案


当从另一个方法调用的方法传递参数时,Spring 不会验证数据。

更好的方法是在发送数据之前设置条件来验证数据。

更新后的代码将是:

@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");
    }
}

推荐阅读