2017-04-15 95 views
0

我有一個像讀取數據控制器使用在春季啓動

1 E 
2 F 
3 A 

一個文本文件,我希望把它變成一個HashMap,並用它在控制器服務鍵值到客戶。我必須把文件在啓動參數,讓我們說

java -jar application.jar [filename] 

我想我必須檢索從SpringBootApplication的主要方法的參數(文件名),把數據放到服務(怎麼傳呢?) ,並將其自動裝入控制器中。 Spring Boot域中的最佳做法是什麼?

回答

2

嘗試一些類似下面的代碼片段:

@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

+0

好吧不錯,但我怎麼能檢索的文件名從控制檯作爲參數。我不必在@Value(「classpath:mapping.txt」)中顯式給出文件名,我必須從控制檯中檢索它。 – uploader33

+0

@ uploader33更新了我的回答 – rvit34

+0

@ rvit34你有沒有試過,如果這將工作?因爲我在遇到正確/不正確的params順序時也碰到類似的問題。我認爲'-D'必須放在'-jar'部分之前,否則它將被解釋爲應用程序參數而不是JVM系統參數。 –