0

I am new to Springboot PropertiesFactoryBean and want to inject a file from classpath so that I can populate it into a Map

Location of properties file on Eclipse: src/main/resources

contents of File: simple_property.properties:

key1=value1
key2=value2
key3=value3

My ApplicationConfiguration.java looks as below:

import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class ApplicationConfiguration {

    @Bean(name = "simpleMapping")
    public static PropertiesFactoryBean artifactMapping() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource("simple_property.properties"));

        return bean;
    }

}

I have a ApplicationRunner interface for bean to be run:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class pCli implements ApplicationRunner {

    @Autowired
    private SomeClass someProgram;

    public static void main(String[] args) {
        SpringApplication.run(pCli.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        someProgram.run(args.getOptionValues("param1").get(0));
    }
}

I am unable to understand & proceed ahead how I can use bean to read all properties ? Example how I can get the properties into a variable of Map and access them ? (If @Autowired has already loaded the properties file from classpath then how can I access it ? )

msashish
  • 277
  • 2
  • 6
  • 18
  • 1
    please check https://stackoverflow.com/questions/30691949/how-to-inject-a-map-using-the-value-spring-annotation – Arvind Gangam Mar 15 '19 at 05:33
  • Thanks Arvind. I used '@Resource' and have moved ahead. When I experimented with @Autowired on a constructor, it did not work. I will go through in debug mode and rectify – msashish Mar 17 '19 at 13:34

1 Answers1

0

Say you have your map in the property file like this,

app.number-map={KEY1:1, KEY2:2, KEY3:3}

You can use this value by injecting the property using the @Value annotation. Following is an example where the value is injected to a method. Spring expression #{${app.number-map}} will fetch the value in the properties file.

someMethod(@Value("#{${app.number-map}}") 
        Map<String, Integer> numberMap) {
   // ...
}

Use application.properties since you're still learning. It'll make your life easy. Also, keeping a separate configuration bean would really help you to manage and access property values easily.

k9yosh
  • 858
  • 1
  • 11
  • 31