When developing applications, many times we need to read resources – e.g., files from the classpath, a URL, or the file system. To make our job easy, Spring provides a Resource interface with many built-in implementations.

Reading resources using the built-in Resource implementations is easy, and you’ll find many examples in the Internet. See this one for example. But, do you know – it’s possible to inject resources into our beans just by using the @Value annotation!

For example, to read a file at /src/main/resources/init/data.json, you can just have the following code in your service class:

@Service
public class SampleService {
    ...
    @Value("classpath:/init/data.json")
    private Resource data;
}

And, to read a list of files, just use wildcards, and inject thoses into an array:

@Service
public class SampleService {
    ...
    @Value("classpath:/init/*.json")
    private Resource[] allData;
}

Remember – you must use an array above. Lists won’t work – not sure why.