我怎样才能在约束上设置弹簧@RestController
属性?javax.validation
我以为我可以添加/src/main/resources/messages.properties
and messages_de.properties
,然后spring
检测它们并启用正确的 i18n?但情况似乎并非如此:
@RestController
public void TestController {
@PostMapping
public void post(@Valid @RequestBody Person p) {
}
}
public class Person {
private String firstname;
@javax.validation.constraints.NotBlank(message = "{errors.person.lastname}")
private String lastname;
}
messages.properties:
errors.person.lastname=person should provide a lastname
messages_de.properties:
errors.person.lastname=Person ohne Nachnamen
问题:如果我现在发送POST
请求:
{
"exception": "org.springframework.web.bind.MethodArgumentNotValidException",
"message": "'lastname': {errors.person.lastname}"
}
问题1:我真的必须告诉spring显式应用i18n吗?或者我可以以某种方式依赖自动检测功能吗?
下一步是添加以下配置。现在默认消息已正确解析。但是,每当我想要验证 i18n 时,是否有必要真正添加它?
@Configuration
public class MessageSourceConfig {
@Bean
public LocalValidatorFactoryBean localValidatorFactoryBean() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource bundle = new ResourceBundleMessageSource();
bundle.setBasenames("messages");
return bundle;
}
}
问题 2:我需要这些 bean:我现在如何发送帖子请求以切换语言?我尝试添加 get-query 参数?local=de, locale=de, ?lang=de, language=de
,但它们都不起作用......