Spring 4 Framework Internationalization无法使用thymeleaf识别来自资源属性文件的消息

时间:2014-02-11 14:46:17

标签: java spring-mvc internationalization thymeleaf

使用带有百里香的新弹簧版本,不是我的专长,有gradle, 我尝试了很多方法更改位置文件和basename的配置,仍然接收?? welcome.message _ ** ??在模板结果。

@EnableAutoConfiguration
@Configuration
@ComponentScan
public class Application {

[...]

@Bean
public ReloadableResourceBundleMessageSource resourceBundleMessageSource(){
        ReloadableResourceBundleMessageSource messageSource=new ReloadableResourceBundleMessageSource();
        String[] resources= {"/WEB-INF/locale/messages", "WEB-INF/locale/messages", "locale/messages", "i18n", "locale"};
        messageSource.setBasenames(resources);
        messageSource.setFallbackToSystemLocale(true);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

@Bean 
public LocaleChangeInterceptor localeChangeInterceptor(){
    LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("lang");
    return localeChangeInterceptor;
}

@Bean
public SessionLocaleResolver sessionLocaleResolver(){
    SessionLocaleResolver localeResolver=new SessionLocaleResolver();
    localeResolver.setDefaultLocale(new Locale("pt","BR"));
    return localeResolver;
}

public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

模板:

<h1 th:text="#{welcome.message}">Welcome!</h1>

src/java/webapp/WEB-INF/local/messages.propertiessrc/java/webapp/WEB-INF/local/messages_pt_BR.properties

上有2个属性

github项目:https://github.com/brunoguerra/springtutorial/tree/master/web-scure-jpa

感谢任何想法

2 个答案:

答案 0 :(得分:4)

走动后,我在github的春季项目中找到了样本。解决方案非常简单,只需在MVC配置器上定义public MessageSource messageSource(),而不是在应用程序配置器上public ReloadableResourceBundleMessageSource resourceBundleMessageSource()

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

[...]

@Bean    
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("/WEB-INF/messages/messages");
    return messageSource;
}

答案 1 :(得分:0)

bean名称应为 messageSource 我们可以做到

@Bean(name ="messageSource")
public MessageSource anyName() {} 

或者

public MessageSource messageSource() {}