如何读取文件并将其分配给 spring 中的 ArrayList?

How to read a file and assign it to an ArrayList in spring?

考虑以下 类:

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. 使用Files.readAllLines(path,cs)阅读input.txt(来自JDK 1.7)
  2. 设置返回值(List<String>)为Store.store
  3. 我想一直使用 Spring 注释(我正在编写一个 spring-boot 应用程序)
  4. 我需要 Store 成为一个 Singleton bean。
  5. 在我的应用程序引导过程中需要初始化商店。

这个问题可能太模糊了,但我完全不知道如何让它更具体。

P.S.
我是 Spring.

的新手

使用构造函数注入似乎是最理想的。

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 上下文读取的属性文件中。您还需要为 Store

添加一个 bean 定义

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

然后你的 Rest Controller 看起来像这样:

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

有几种不同的方法来编写注入和控制器,因此请进行一些研究并使用最适合您需要的方法。