2017-09-10 58 views
2

我有一個使用國家明智的配置文件的春季啓動應用程序。配置文件的結構相同,但不同國家/地區的值不同。加載春季啓動的上下文配置

我在資源目錄中爲每個國家創建了一個目錄,並將該國家的配置文件放在那裏。

基於在請求參數中傳遞的國家代碼,我想使用相應的配置文件。什麼是春季啓動慣用的方式來實現這(除了手動加載yaml配置文件使用類似snakeyaml)?

感謝

回答

2

你可以使用Spring @Profile每個國家。見examplesdocs

彈簧配置文件提供了一種將應用程序的部分配置分離並使其僅在特定環境中可用的方法。任何 @Component或@Configuration可以@profile標記限制時 它被加載:

您可以在運行時添加簡介:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
    ctx.getEnvironment().setActiveProfiles("za"); 
+0

據我所知,你必須告訴spring boot在啓動時加載哪個配置文件(例如dev,s分期,產品等)。就我而言,它是基於請求的。/getData?countryCode = za,/ getData?countryCode = in etc,我必須使用適當的配置文件(za/config.yaml和/ config.yaml)來爲每個請求提供服務。正在使用配置文件正確的方法嗎? – Vikk

+0

您可以編程添加它:'AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment()。setActiveProfiles(「za」);' – user7294900

5

可以通過爲MessageSource創建豆acheive ,LocaleResolverLocaleChangeInterceptor bean,然後添加到LocaleChangeInterceptorInterceptorRegistry這樣的:

@Configuration 
    public class CountryConfig extends WebMvcConfigurerAdapter{ 

     @Bean 
     public MessageSource messageSource() { 
      ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
      messageSource.setBasenames("classpath:country-conf/country"); 
      messageSource.setUseCodeAsDefaultMessage(true); 
      messageSource.setDefaultEncoding("UTF-8"); 
      messageSource.setCacheSeconds(3600); 
      return messageSource; 
     } 

     @Bean 
     public LocaleResolver localeResolver() { 
      SessionLocaleResolver slr = new SessionLocaleResolver(); 
      slr.setDefaultLocale(Locale.US); 
      return slr; 
     } 

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

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

然後在resources文件夾中創建文件夾country-conf。在這個文件夾內創建屬性文件,它將會有你的配置。例如:

country.properties(默認)

country.name=United states 

country_fr.properties

country.name=France 

country.properties是默認屬性,如果沒有國家的參數發送,如果您發送country=fr在參數中,它會查找country_fr.properties文件。

現在創建一個服務,將來自這些屬性獲得價值文件基於國家參數

@Service 
public class CountryService { 

    @Autowired 
    private MessageSource messageSource; 

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

爲了測試這個自動裝配國服

@Autowired 
CountryService countryService; 

然後調用getMessage方法

countryService.getMessage("country.name");