I work for the first time with the Spring Framework, and faced with the fact that I can not add my sources of property. The following code:

@Bean public static YamlPropertiesFactoryBean yamlProperties() { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(new ClassPathResource("application.yml")); return factory; } @Bean public static PropertyPlaceholderConfigurer propertyPlaceholder() { PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); configurer.setProperties(yamlProperties().getObject()); return configurer; } 

It works correctly, I can drop an arbitrary property to the logger, the methods themselves are executed, but in the environment these properties are not added (ie, environment.getProperty() does not return to me the value that I can get through yamlProperties.getObject().getProperty() ) WHERE and how do I add my configuration to the application?

    1 answer 1

    Ny

    Climb hands in Environment . These are guts that you shouldn't crawl into without. Doc on Environment says:

    In most cases, however, it is not necessary to directly interact with the environment.

    If you just want to reach the loaded prop in the code, inject them into the required bins via @Value and placeholders:

     public class SomeBean { @Value("${mybeans.foo}") private String foo; private String bar; @Value("${mybeans.baz}") private String baz; ... } 

    Ad-hoc can be pulled out of context so:

     ctx.getBeanFactory().resolveEmbeddedValue("${mybeans.foo}") 

    Ps. Starting with Spring 3.1, it is recommended to use PropertySourcesPlaceholderConfigurer instead of PropertyPlaceholderConfigurer .


    Pps. If you still really want to pour the property in the Environment and then shoot yourself on the legs, you can do this:

     PropertySourcesPlaceholderConfigurer prop = (PropertySourcesPlaceholderConfigurer) ctx.getBean(PropertySourcesPlaceholderConfigurer.class); Iterator<PropertySource<?>> iterator = prop.getAppliedPropertySources().iterator(); while (iterator.hasNext()) { ctx.getEnvironment().getPropertySources().addFirst(iterator.next()); } 
    • Hmm, I was sure that everything should be run through the environment, and getProperty () in variations is the only entry point (and @Value passes through it the same). Thank. - etki