简体   繁体   中英

How to inject a network file resource with Spring?

How can I tell Spring that the resource is supposed to be a network resource, and let it autowire accordingly?

@Value("\\MY-MACHINE\thefile.txt")
private Resource file;

Result:

Caused by: java.io.FileNotFoundException: class path resource [MY-MACHINE\thefile.txt] cannot be resolved to URL because it does not exist

I am assuming your application is deployed on Windows. I don't have anywhere windows workstation to test it, but as far as I remember this is how it goes:

  • create symbolic link to your network location:

     mklink /DC:\\my-machine \\\\MY-MACHINE\\ 
  • refer to this symlink with absolute path:

@Value("file:///C:/my-machine/thefile.txt")
private Resource file;

As nobody seems to be aware of, I found out that it's just necessairy to use double slashes like:

@Value("\\\\MY-MACHINE\\thefile.txt")
private Resource file;

In some cases you may required a file: statement before, like: file:\\\\\\\\MY-MACHINE\\\\thefile.txt"

This is the easiest way using classpath

import org.springframework.core.io.Resource;

@Value("classpath:<path to file>")
private Resource file;

Accessing a file on a Windows share will not work directly. See connecting to shared folder in windows with java for more info on how to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM