I have to load file from outside of my classpath. The location depends of env properties:
/location/file)What is the best way to do it?
A possible solution is to use configuration properties and the use of Resource. For example, define your properties like this:
@ConfigurationProperties(prefix = "app")
public class SomeProperties {
private Resource file;
// Getters + Setters
}
Then enable your configuration properties by using the @EnableConfigurationProperties annotation on any class, for example your main class:
@SpringBootApplication
@EnableConfigurationProperties(SomeProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
To configure the file location, you can use the following in development:
app.file=classpath:test.txt
And in the production environment you could use:
app.file=file:/usr/local/test.txt
And now you can just autowire the SomeProperties class within any other service. The Resource class has a getFile() method that allows you to retrieve the file, but in addition it contains several other useful methods as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With