2017-10-13 33 views
0

我想根據HttpServletRequest加載一組不同的messages_xx.properties,以根據我們的客戶區分它們。Spring引導 - 基於請求的不同messages.properties

模板,並通過所有的應用程序,我們有一個@Bean這給基於請求

@Component 
public class CompanySelector { 

    @Autowired 
    private ICompanyService service; 

    public String getURLBase(HttpServletRequest request) throws MalformedURLException { 
     URL requestURL = new URL(request.getRequestURL().toString()); 
     String port = requestURL.getPort() == -1 ? "" : ":" + requestURL.getPort(); 
     return requestURL.getHost() + port; 
    } 

    public Company getActualCompany(HttpServletRequest request) throws MalformedURLException{ 
     String url = getURLBase(request); 

     Company company = service.findByCompanyUrl(url); 
     if(company != null){ 
      return company; 
     } 
     return null; 
    } 

} 

現在的路徑上的實際客戶,我們配置MessageSourceWebConfig延伸WebMvcConfigurerAdapter,我們將喜歡做這樣的事情

@Configuration 
@ComponentScan("it.besmart.eshare.web") 
public class WebConfig extends WebMvcConfigurerAdapter{ 

    public WebConfig(){ 
     super(); 
    } 

    @Autowired 
    CompanySelector companySelector; 

    @Autowired 
    HttpServletRequest request; 

    @Bean 
    public MessageSource messageSource() { 
     ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
     Company company = null; 
     try { 
      company = companySelector.getActualCompany(request); 
     } catch (MalformedURLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     if (company != null){ 
      messageSource.setBasename("classpath:"+ company.getSlug() + "_messages"); 
     } else { 
      messageSource.setBasename("classpath:messages"); 
     } 
     messageSource.setDefaultEncoding("UTF-8"); 

     return messageSource; 
    } 

} 

但很明顯,因爲我們沒有配置的過程中要求它不工作...是否有另一種方式來加載基礎上,reque消息文件ST?或採取其他最佳做法?因爲我們的其他選擇是每個語言只使用一個文件,並在每個短語的開頭使用company.getSlug(),但是我們會刪除文件的大小...

+0

你可以依靠,而不是使用'company.getSlug()'對瀏覽器語言環境? –

+0

它不是語言環境的問題,它是文件上的問題..我有company1_messages_us.properties,company1_messages_fr.properties,company2_messages_us.properties,company2_messages_fr.properties等等... – besmart

回答

0

您需要聲明每個屬性文件即:

@Bean 
public MessageSource messageSource() { 
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
    messageSource.setBasenames("company1_messages", "company2_messages"); 
    messageSource.setDefaultEncoding("UTF-8"); 
    return messageSource; 
} 

而且得到的消息:

@Autowired 
private MessageSource messageSource; 

public String myRequest(Locale locale) { 
    ... 
    messageSource.getMessage(company.getSlug().".messageKey1", null, locale)); 
    ... 
} 

company1_messages_fr.properties

company1.messageKey1=messageCompany1 

company2_messages_fr.properties

company2.messageKey1=messageCompany2