2017-05-26 93 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

这正是我一直在寻找的。谢谢 –

相关问题