考虑以下类:
public class Store {
private final ArrayList<String> store;
public ArrayList<String> getStore() {
return store;
}
public Store(ArrayList<String> store){
this.store = store;
}
}
我有一个名为 input.txt
的文本文件
我有一个普通 Controller ,其注释为 @RestController
如下:
@RestController
@RequestMapping(value="/test")
public class Controller {
.
.
.
}
我需要执行以下操作:
- 使用
Files.readAllLines(path,cs)
读取 input.txt (从 JDK 1.7 开始) - 将返回值(
List<String>
)设置为Store.store
- 我想一直使用 Spring 注解(我正在编写一个 spring-boot 应用程序)
- 我需要 Store 成为 Singleton bean。
- 商店需要在我的应用程序引导期间初始化。
这个问题可能太模糊了,但我完全不知道如何使其更具体。
附注
我是 Spring 的新手。
最佳答案
看起来使用构造函数注入(inject)是理想的选择。
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" />
然后你的休息 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;
}
}
有几种不同的方法来编写注入(inject)和 Controller ,因此请进行一些研究并使用最适合您需求的方法。
关于java - spring中如何读取文件并将其分配给ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44202930/