2017-03-06 76 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来手动绑定它们。