3

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?

g00glen00b
  • 41,995
  • 13
  • 95
  • 133
michf
  • 209
  • 6
  • 17

1 Answers1

7

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.

g00glen00b
  • 41,995
  • 13
  • 95
  • 133
  • 1
    I have something like this working. However, how can I create the `File`/`Resource` if it doesn't exist yet? (e.g. Create the file when running for the first time) – Jack Straw Oct 27 '20 at 22:26
  • @JackStraw I don't think spring throws an exception if it doesn't exist, so you can use one of the many answers found in [this question](https://stackoverflow.com/q/9620683/1915448) to create the file if it doesn't exist. – g00glen00b Oct 28 '20 at 00:05