membersound
membersound

Reputation: 86915

How to inject a properties file using Spring?

How can I inject the following key-value file as a Properties variable or HashMap directly, using spring?

src/main/resources/myfile.properties:

key1=test
someotherkey=asd
(many other key-value pairs)

None of the following worked:

@Value("${apikeys}")
private Properties keys;

@Resource(name = "apikeys")
private Properties keys;

Sidenote: I don't know the keys inside the properties file in advance. So I cannot use @PropertyResource injection.

Upvotes: 4

Views: 4353

Answers (3)

randomUser56789
randomUser56789

Reputation: 936

One way you could try to achieve this is by creating a bean in your configuration file:

@Bean
public Map<String, String> myFileProperties() {
    ResourceBundle bundle = ResourceBundle.getBundle("myfile");
    return bundle.keySet().stream()
            .collect(Collectors.toMap(key -> key, bundle::getString));
}

Then you can easily inject this bean into your service e.g.

@Autowired
private Map<String, String> myFileProperties;

(Consider using constructor injection)

Also don't forget to

@PropertySource("classpath:myfile.properties")

Upvotes: 2

Kiran
Kiran

Reputation: 20293

You can use Annotation PropertySource:

Sample:

@PropertySource("myfile.properties")
public class Config {

    @Autowired
    private Environment env;

    @Bean
    ApplicationProperties appProperties() {
        ApplicationProperties bean = new ApplicationProperties();
        bean.setKey1(environment.getProperty("key1"));
        bean.setsomeotherkey(environment.getProperty("someotherkey"));
        return bean;
    }
}

Upvotes: 0

Amit
Amit

Reputation: 32386

In order to use Value annotation first you need to define in your applicationContext.xml below bean

<bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:myfile.properties"></property>
</bean> 

Once you define your property file , you can use Value annotation.

Upvotes: 1

Related Questions