Load resource/file from test/resources using Spring

Viewed 2465

Is it possible to load a File/Resource from Maven's test/resources directory using @Value?

e.g. something like this:

@Value("${test/resources/path/to/file}") File file 

EDIT:

I tried this:

@Value("${someFile}") FileSystemResource file;

but at runtime I see that it represents the working directory and not the file that in test/resources

3 Answers

Anything from test/resources is copied to target/test-classes just before the test phase. Those copied resources will be available on the classpath.

If you start a Spring Configuration in your test classes, there is a binding for classpath resources that allows you to inject them like this:

   @Value("classpath:path/to/file")
   Resource resourceFile;

It isn't necessary a File, since it could also come from a jar file on the classpath, but you can read it via the InputStream etc.

Not sure if there is direct way to do this.

This is alternate approach we used to initialize it through constructor:

@RestController
public class FileController {

    private File file;

    public FileController(@Value("${file-name}") String filename) {
        file = new File(filename);
    }

}

You can use ResourceUtils to load files.

Example: File certFile = ResourceUtils.getFile("classpath:certs/cert.txt");

Then you can process it using InputStream like below: InputStream inputStream = new FileInputStream(certFile);

Related