Domanda

I have the following configuration piece on my xml file:

<util:properties id="apiConfigurator" location="classpath:api.properties" scope="singleton"/>

And here is my properties file:

appKey=abc
appSecret=def

On my spring classes I get some of the values like this:

@Value("#{apiConfigurator['appKey']}")

I would like to create a @Configuration class in Spring to parse the properties file in a way that

@Value("#{apiConfigurator['appKey']}")

still works thorough my classes that use this. How do I properly do that?

È stato utile?

Soluzione

When you specify

<util:properties .../>

Spring registers a PropertiesFactoryBean bean with the name/id that you also specified.

All you need to do is to provide such a @Bean yourself

// it's singleton by default
@Bean(name = "apiConfigurator") // this is the bean id
public PropertiesFactoryBean factoryBean() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("api.properties"));
    return bean;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top