springboot 2中的语言环境

时间:2018-10-05 13:09:14

标签: java spring-boot spring-data-jpa

我尝试在我的spring-boot 2应用程序中使用I18N

首先,我在资源/语言环境/消息中创建一个名为“ messages_pt_BR.properties”的文件,

Size.Ato.sercicos=Deve conter pelo menos 1 item
Size.atoRtdpj.servicos=Deve conter pelo menos 1 item
Size.servicos=msg1
Size=msg2
validacao_documento_obrigatorio=Documento: Pelo menos 1 precisa estar preenchido

然后我创建

@Configuration
public class LocaleConfiguration {

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        Locale.setDefault(new Locale("pt","BR")); // without this line when I try to get the locale the system return en_BR
        localeResolver.setDefaultLocale(new Locale("pt","BR"));
        return localeResolver;
    }

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:locale/messages");
        messageSource.setCacheSeconds(3600); //refresh cache once per hour
        return messageSource;
    }
}

然后我创建

@Component
public class Messages {

    @Autowired
    private MessageSource messageSource;

    public String getMessage(String id) {
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage(id,null,locale);
    }

}

因此在我的控制器中,我使用:

@Autowired
Messages messages;

//in my method:

messages.getMessage("validacao_documento_obrigatorio")

当我尝试对此进行测试时,会返回此错误:

org.springframework.context.NoSuchMessageException: No message found under code 'validacao_documento_obrigatorio' for locale 'pt_BR'.

并且jpa约束不会更改。

1 个答案:

答案 0 :(得分:3)

如果您想从inline加载,请在messages_pt_BR.properties下移动locale,因为这会在locale文件夹下搜索classpath:locale/messages,因此如果您想在{{1}下},那么您需要传递如下所示的完整文件名路径,因为它将加载messages_pt_BR property文件夹下的/locale/messages文件:

messages_pt_BR