java - 如何验证从同一类调用的方法的参数?
问题描述
对于从“@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"?
}
}
解决方案
当从另一个方法调用的方法传递参数时,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");
}
}
推荐阅读
- html - 我不能让 col-8 与 col-4 并排渲染?
- stata - 将变量从字符串转换为数字
- javascript - 如何遍历非常大的列表并使用它创建高效的 JSON NODEJS
- javascript - 为什么提升结果数组会使递归按预期工作?
- python - 具有不同 x(或 y)范围的不同字符串的轴标签
- git - Git - 不小心提交并推送了数千张图片 - 我如何在没有提交的情况下推送?
- c# - 在 ASP.NET MVC 视图中显示来自 .NET Core API 的图像是否正确?
- php - 在预订计算器中计算不同日期的价格
- spring-boot - Spring Data Rest 仅显示链接但不显示信息
- powerbi - 使用选定月份过滤器中最近一个月的 DAX 月份与去年月份