我想以请求的 Accept-Language HTTP 标头定义的语言返回 Java Bean 验证消息。对此的配置应该通过库中的 Spring Autoconfiguration 来完成。
定义一个 beanLocaleContextResolver
不会改变消息的语言。在处理程序的方法中定义一个 beanHttpHandler
并解析语言createExchange()
确实有效。但是,Spring Autoconfiguration 不再可能,说明HttpHandler
定义了两个 bean。
如何使用 Spring WebFlux 和 Spring Autoconfiguration 基于 Accept-Language HTTP 标头设置 Java Bean 验证消息的语言?
下面是对所有消息使用 Accept 标头语言的代码。但是,它不适用于 Spring Autoconfiguration,因为它定义了一个 Bean,HttpHandler
并且只允许使用一个这种类型的 Bean。
@Bean
MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("messages-commons", "messages/messages");
messageSource.setDefaultLocale(Locale.ENGLISH);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Bean
LocalValidatorFactoryBean localValidatorFactoryBean() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
@Bean
HttpHandler acceptLanguageHeaderHttpHandler(ApplicationContext applicationContext) {
HttpHandler delegate = WebHttpHandlerBuilder.applicationContext(applicationContext).build();
return new HttpWebHandlerAdapter((HttpWebHandlerAdapter) delegate) {
@Override
@NonNull
protected ServerWebExchange createExchange(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) {
ServerWebExchange serverWebExchange = super.createExchange(request, response);
LocaleContext localeContext = serverWebExchange.getLocaleContext();
Locale requestedLocale = localeContext.getLocale();
if (requestedLocale != null && supportedLocales.stream()
.anyMatch(locale -> locale.getLanguage().equals(requestedLocale.getLanguage()))) {
LocaleContextHolder.setLocaleContext(localeContext);
} else {
LocaleContextHolder.setLocaleContext(() -> Locale.ENGLISH);
}
return serverWebExchange;
}
};
}