2017-05-26 75 views
1

考慮下面的類:如何在春天讀取文件並將其分配給ArrayList?

public class Store { 
    private final ArrayList<String> store; 
    public ArrayList<String> getStore() { 
     return store; 
    } 
    public Store(ArrayList<String> store){ 
     this.store = store; 
    } 
} 

我有一個名爲input.txt
我有標註有@RestController正常控制器的文本文件,如下所示:

@RestController 
@RequestMapping(value="/test") 
public class Controller { 

    . 
    . 
    . 

} 

我需要做的以下操作:

  1. 閱讀input.txt中使用Files.readAllLines(path,cs)(JDK從1.7)
  2. 將返回值(List<String>)到Store.store
  3. 我想使用Spring註解一路(我正在寫一個彈簧啓動應用程序)
  4. 我需要Store作爲一個Singleton bean。
  5. 商店需要在自舉應用程序的過程中進行初始化。

這個問題可能太模糊了,但我完全不知道如何使它更具體。

P.S.
我是Spring的新手。

+0

我有幾個問題應該讓你的問題更加具體化...... 1)你是否試圖製作一個RESTful Web服務?如果是這樣,這個文件是否需要傳遞給服務器,它是在服務器上,還是在用戶的本地機器上? 3)當你說arrayList 存儲,這是一個商店名稱列表?你可以期待什麼格式的input.txt? – Steve

+0

https://stackoverflow.com/questions/1363310/auto-wiring-a-list-using-util-schema-gives-nosuchbeandefinitionexception and https://www.mkyong.com/spring/spring-value-import-a -list-from-properties-file/ – StanislavL

+0

是的,我正在嘗試製作一個RESTful WS。 和input.txt在服務器上是UTF-8格式。 –

回答

2

這似乎是使用構造函數注入將是理想的。

public class Store { 
    private final List<String> storeList; 

    @Autowired 
    public Store(@Value("${store.file.path}") String storeFilePath) throws IOException { 
      File file = new File(storeFilePath); 
      storeList = Files.readAllLines(file.toPath()); 
    } 
} 

您需要將store.file.path屬性添加到由spring上下文讀入的屬性文件中。你也將要增加一個bean定義店鋪

<bean id="Store" class="com.test.Store" />

然後你休息控制器可以是這個樣子:

@RestController 
@RequestMapping(value="/store") 
public class StoreRestController { 

    @Autowired 
    Store store; 

    @RequestMapping(value="/get", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 
    public ResponseEntity<Store> getStore(HttpServletRequest request) { 
     ResponseEntity<Store> response = new ResponseEntity<Store>(store, HttpStatus.OK); 
     return response; 
    } 
} 

有一對夫婦不同的方式來寫你的注射&控制器,以便做一些研究和使用最適合您需求的方法。

+1

我會考慮添加緩存,因爲讀取文件是繁重的操作,應該只做一次 – nowszy94

+1

該文件每個Store實例只需要一次,所以如果bean使用默認的'singleton'作用域,那麼文件將被獲取只是一次 – jlumietu

+0

這正是我一直在尋找的。謝謝 –

相關問題