繁体   English   中英

在Spring Boot中从控制器中开始使用时从文件中读取数据

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

我有一个像文本文件

1 E
2 F
3 A

我想将它放入HashMap并在控制器中使用它来为客户端提供键值。 我要说,我必须在开始时将文件作为参数

java -jar application.jar [filename]

我想我必须从SpringBootApplication的main方法中检索参数(filename),将数据放入服务(如何传递它?),并在控制器中自动装配它。 在Spring Boot域中执行此操作的最佳做​​法是什么。

尝试类似于下一个代码段的内容:

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

运行java -Dmapping=mapping.txt -jar application.jar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM