How to insert a properties file using Spring?

How can I insert the following key value file as a variable Properties

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 beforehand. Therefore I cannot use injection @PropertyResource

.

+3


source to share


3 answers


To use annotation first Value

, you need to define in 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 properties file, you can use annotation Value

.

+2


source


One way to achieve this is to create a bean in the config 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 for example.

@Autowired
private Map<String, String> myFileProperties;

      



(consider using constructor inset)

Also don't forget

@PropertySource("classpath:myfile.properties")

+1


source


You can use PropertySource annotation :

Example:

@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;
    }
}

      

0


source







All Articles