Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot - load file from outside classpath

I have to load file from outside of my classpath. The location depends of env properties:

  • in dev properties I want to load file from resources folder
  • in prod properties I want to load file from path (/location/file)

What is the best way to do it?

like image 427
michf Avatar asked Dec 04 '25 23:12

michf


1 Answers

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.

like image 189
g00glen00b Avatar answered Dec 06 '25 13:12

g00glen00b



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!