2

I have a text file like

1 E
2 F
3 A

I want to put it into a HashMap and use it in the controller to serve key-value to the client. I have to take the file as argument at start, let's say

java -jar application.jar [filename]

I think I must retrieve the argument(filename) from main method of the SpringBootApplication, put the data into a service (how to pass it?), and Autowire it in the controller. What is the best practice to do it in Spring Boot domain.

uploader33
  • 308
  • 1
  • 5
  • 16

1 Answers1

5

Try something similar to the next code snippet:

@Configuration
public class Config {
    private final static Logger logger = LoggerFactory.getLogger(Config.class);

    @Value("classpath:#{systemProperties.mapping}")
    // or @Value("file:#{systemProperties.mapping}")
    private Resource file;

    @Bean(name="mapping")
    public Map<Integer,Character> getMapping() {
        Map<Integer,Character> mapping = new HashMap<>();
        try(Scanner sc = new Scanner(file.getInputStream())) {
            while(sc.hasNextLine()){
                mapping.put(sc.nextInt(),sc.next().charAt(0));
            }
        } catch (IOException e) {
            logger.error("could not load mapping file",e)
        }
        return mapping;
    }

}

@Service
public class YourService {

    private final static Logger logger = LoggerFactory.getLogger(YourService.class);

    @Autowired
    @Qualifier("mapping")
    private Map<Integer,Character> mapping;

    public void print(){
        mapping.forEach((key, value) -> logger.info(key+":"+value));
    }
}

@SpringBootApplication
public class SpringLoadFileApplication {

    public static void main(String[] args) {

        ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(SpringLoadFileApplication.class, args);
        YourService service = configurableApplicationContext.getBean(YourService.class);
        service.print();
    }
}

Run program like java -Dmapping=mapping.txt -jar application.jar

rvit34
  • 1,967
  • 3
  • 17
  • 33
  • Alright nice, but how can I retrieve filename from console as argument. Instead of explicitly giving filename here @Value("classpath:mapping.txt") , I must retrieve it from console. – uploader33 Apr 15 '17 at 11:17
  • @rvit34 did you tried if that will work? Cause I ran into a similar issue also once given the correct/incorrect order of params. I think the `-D` has to go before the `-jar` part cause otherwise it will be interpreted as an application param and not a JVM system param. – daniel.eichten Apr 15 '17 at 13:45
  • @daniel.eichten I tried it from IDE and it worked. Yeah. You are right. Made correction. Also I should notice that file should be located inside a jar. Otherwise `@Value("file:#{systemProperties.mapping}")` should be used – rvit34 Apr 15 '17 at 14:23
  • https://stackoverflow.com/questions/43472459/restart-spring-boot-when-input-text-file-changes could you please look at this? – uploader33 Apr 18 '17 at 12:42