将String转换为Spring资源的方法

Nik*_*han 8 string resources spring

我有一个类在Spring(org.springframework.core.io.Resource)中具有Resource类型的资源属性,它将文件对象作为输入.

setResource(Resource resource) 
  {
     this.resource = resource;
  }
Run Code Online (Sandbox Code Playgroud)

但是,我正在通过另一个自定义API读取远程文档,该API将文档的内容作为String返回.

String xml = document.getContent();
Run Code Online (Sandbox Code Playgroud)

我想像Resource我的setResource方法一样传递这个xml .但是,我不知道如何将String转换为Resource.

有任何想法吗 ??

ska*_*man 19

您可以ByteArrayResource从String中创建一个:

String xml = document.getContent();
Resource resource = new ByteArrayResource(xml.getBytes());
setResource(resource);
Run Code Online (Sandbox Code Playgroud)

  • @Nikunj:因为`InMemoryResource` 不是Spring 的一部分,而是Spring Security 的一部分。如果你有,那么它会工作得很好。 (2认同)