Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 228
yaseco Avatar asked Jan 17 '26 21:01

yaseco


1 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.

like image 105
GeertPt Avatar answered Jan 20 '26 11:01

GeertPt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!