英文:
How to validate parameters of methods that calling from same class?
问题
以下是翻译好的内容:
从“@Autowired”父类调用 bean 类方法时,验证按预期工作。但如果从类本身调用内部方法,该如何验证?
@Bean
@Validated
public class TestBean {
public void testMethod(@NotNull String param1) {
System.out.println("在 TestBean.test 中");
this.innerMethod(null);
}
private void innerMethod(@NotNull String param1) {
System.out.println("在 TestBean.innerMethod 中");
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class TestBeanTest {
@Autowired
private TestBean bean;
@Test
public void testMethod() {
bean.testMethod(null); // -> 预期的错误
bean.testMethod("example"); // -> 在 "inner method" 中没有 ConstraintValidation 错误,如何验证 "innerMethod"?
}
}
英文:
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"?
}
}
答案1
得分: 1
Spring在从另一个方法调用的方法中传递参数时不会验证数据。
更好的方法是在发送数据之前设置条件来验证数据。
更新后的代码将是:
@Bean
@Validated
public class TestBean {
@Autowired
private Service Service;
public void testMethod(@NotNull String param1) {
System.out.println("在TestBean.test中");
// 假设有一些调用。
String arbitrary = service.getSomeStringData(param1);
// 在发送之前进行验证。
if(arbitrary != null) {
this.innerMethod(arbitrary);
}
}
private void innerMethod(String param1) {
System.out.println("在TestBean.innerMethod中");
}
}
英文:
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");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论