2017-03-06 33 views
1

我的應用程序基於spring,我想從中央服務器加載yml文件,但無法這樣做。如何使用Spring框架使用YAML文件?

我YML文件是這樣的:

spring: 
    application: 
    name: signed-in-web 
    cloud: 
    config: 
     uri: ${server.url} 
health: 
    config: 
    enabled: false 

注:server.url在虛擬機選項定義。 我已經從其他客戶端檢查了服務器上的屬性是有效的和可用的。

然後我試圖複製在這樣一個屬性文件: application.properties中

LOCATION_SEARCH=${properties.app.api-key.location-search} 

我的java配置類是這樣的:

@Profile("!test") 
@ComponentScan(basePackages = { "com.company.frontend.*" }) 
@Configuration 
@PropertySource("classpath:properties/qa_env.properties") 
public class propertiesConfig { 

    @Bean 
    public static PropertySourcesPlaceholderConfigurer properties() { 
     PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); 
     YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); 
     yaml.setResources(new ClassPathResource("bootstrap.yml")); 
      propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject()); 
     return propertySourcesPlaceholderConfigurer; 
    } 
} 

我認爲,這將加載像這樣的配置:

@Value("${LOCATION_SEARCH}") 
public static String LOCATION_SEARCH; 

但我變空了。不知何故,我無法找到問題所在。將

回答

1

如果您使用Spring Boot,則只需將其稱爲application-qa.yaml並啓用qa配置文件。另請參閱spring.configspring.profilesCommon Application Properties

否則,您只需要在@PropertySource@PropertySources中聲明yaml文件。

只有當您不希望全球環境中的屬性時,您是否需要使用PropertiesConfigurationFactoryYamlPropertiesFactoryBean來手動綁定它們。