Consider the following classes:
public class Store {
private final ArrayList<String> store;
public ArrayList<String> getStore() {
return store;
}
public Store(ArrayList<String> store){
this.store = store;
}
}
I have a text file called input.txt
I have a normal controller which is annotated with @RestController
as follows:
@RestController
@RequestMapping(value="/test")
public class Controller {
.
.
.
}
I need to do the following operations:
Files.readAllLines(path,cs)
(from JDK 1.7)List<String>
) to Store.store
This question might be too vague, but I have absolutely no idea about how to make it more specific.
P.S.
I'm a newbie to Spring.
It seems like using Constructor Injection would be ideal.
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());
}
}
you will want to add the store.file.path property to your properties file that is read in by your spring context. You will also want to add a bean definition for Store
<bean id="Store" class="com.test.Store" />
Then your Rest Controller can look something like this:
@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;
}
}
There's a couple different ways to write your injection & controller so do some research and use the method that best suites your needs.