0

I am getting resource with the following manner.

@Value("classpath:user-pass.json")
private Resource resource;

I want to set a default value for the resource if the above resource not found. We can set default value in property extraction as follow

@Value("${some.key:my default value}")
private String string;

I need help in applying a similar formula to resource acquiration.

Resource above is from

package org.springframework.core.io
Davis
  • 188
  • 1
  • 13
  • Can you please add the `Resource` class definition? Or is it https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/Resource.html? – João Dias Sep 21 '21 at 18:16
  • @JoãoDias yes that one – Davis Sep 21 '21 at 18:21
  • The same will work for a `Resource`. The type doesn't matter. – M. Deinum Sep 22 '21 at 05:31
  • @M.Deinum but could not find the syntax for that. can you clarify? There is already colon. – Davis Sep 22 '21 at 16:11
  • There is no difference. See https://stackoverflow.com/a/31711412/2696260 just do `${some.key:classpath:user-pass.json}` (assuming you are on Spring 4.2 or up) and it should just work. – M. Deinum Sep 23 '21 at 05:21
  • ${classpath:model.json:classpath:default.json} does not work. – Davis Sep 23 '21 at 17:55

1 Answers1

0

I don't think this is possible. I would say that your best option would be to load the Resource yourself if it is null after Bean creation:

@PostConstruct
private void postConstruct() {
    if (resource == null) {
        resource = new ClassPathResource("default.json");
    }
}
João Dias
  • 16,277
  • 6
  • 33
  • 45