uploader33
uploader33

Reputation: 328

Reading data from file at start to use in controller in Spring Boot

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.

Upvotes: 2

Views: 6489

Answers (1)

rvit34
rvit34

Reputation: 2116

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

Upvotes: 5

Related Questions