0

My problem: how can I inject a File in my class using the Environment variable?

I specify in a properties the path of a file I need to read:

myFile.path=classpath:myFile.json

I used to have an XML application context defining a property-placeholder for that properties.file and then I simply could inject my file using the @Value:

@Value("${myFile.path}")
private File myFile;

Yet, now I'd like to do something like:

@Inject
private Environment environment;

private File myFile;

@PostConstruct
private void init() {
    myFile = environment.getProperty("myFile.path", File.class);
}

But an Exception is thrown:

Caused by: java.io.FileNotFoundException: 
    classpath:myFile.json (No such file or directory)

I also tried something like myFile = environment.getProperty("myFile.path", Resource.class).getFile(); but an other exception is thrown.

How can I achieve to inject my file knowing that the path defined in the properties can be absolute or classpath relative?

1 Answer 1

2

You can try injecting the ResourceLoader, and use it to load the referenced classpath resource:

@Autowired
private ResourceLoader resourceLoader;

...

@PostConstruct
private void init() {
    String resourceReference = environment.getProperty("myFile.path");
    Resource resource = resourceLoader.getResource(resourceReference);
    if (resource != null) {
        myFile = resource.getFile();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.