使用Thymeleaf发送多语言邮件如何手动指定Locale实现动态翻译
核心问题原因
你配置的LocaleResolver、LocaleChangeInterceptor均为Web请求场景服务,后台触发邮件发送的场景不依赖请求/系统的Locale设置,所以调整Resolver类型不会生效,直接在构造Thymeleaf上下文时手动指定收件人对应的Locale即可。
具体修改步骤
1. 调整邮件发送方法入参,新增Locale参数
在发件方法中新增Locale类型的入参,调用方法时直接传入预先获取到的收件人对应语言的Locale实例即可。
// 方法新增recipientLocale入参,调用时传入收件人对应的Locale public void sendMessageUsingThymeleafTemplate(String to, String subject, Map<String, Object> templateModel, String appName, Locale recipientLocale) throws MessagingException { // 构造Context时直接传入指定的Locale,覆盖默认的上下文Locale Context thymeleafContext = new Context(recipientLocale); thymeleafContext.setVariables(templateModel); String htmlBody; // 修正字符串比较写法,避免空指针和判断失效 if ("Test1".equals(appName)){ htmlBody = thymeleafTemplateEngine.process("Test1-template", thymeleafContext); } else { htmlBody = thymeleafTemplateEngine.process("Test2-template", thymeleafContext); } sendHtmlMessage(to, subject, htmlBody); }
2. 修正MessageSource的basename配置
你当前的配置和properties文件名不匹配,需要调整配置才能正确加载多语言资源:
@Bean public ReloadableResourceBundleMessageSource emailMessageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); // 匹配你mail.messages_xx_XX.properties的命名规则,classpath前缀说明从类路径加载资源 messageSource.setBasename("classpath:mail.messages"); // 设置编码避免中文乱码 messageSource.setDefaultEncoding("UTF-8"); return messageSource; }
3. 调用方法时传入对应Locale
根据你预先拿到的收件人语言,构造对应的Locale实例传入方法即可,示例:
// 示例1:收件人为中文用户 Locale userLocale = Locale.SIMPLIFIED_CHINESE; // 示例2:收件人为法语用户 // Locale userLocale = Locale.FRANCE; // 示例3:通过语言标签动态构造 // Locale userLocale = Locale.forLanguageTag("en-US"); sendMessageUsingThymeleafTemplate(to, subject, templateModel, appName, userLocale);
内容的提问来源于stack exchange,提问作者mariedurand158
相关产品推荐
相关产品推荐

