IsaacLevon
IsaacLevon

Reputation: 2580

Load resource/file from test/resources using Spring

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

Upvotes: 2

Views: 9939

Answers (3)

Patrick Mutwiri
Patrick Mutwiri

Reputation: 1361

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);

Upvotes: 0

GeertPt
GeertPt

Reputation: 17874

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.

Upvotes: 8

Hemant
Hemant

Reputation: 1438

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);
    }

}

Upvotes: 0

Related Questions