membersound
membersound

Reputation: 86915

How to inject Optional<Resource> only if file exists?

Can I tell spring to inject the resource only if the resource file really exists? Because for the following, res.isPresent() is always true if the property my.path.to.file was defined. But I only want it to be true if the resource behind really exists.

@Value("${my.path.to.file}")
private Optional<Resource> res;

Upvotes: 2

Views: 591

Answers (1)

Ivan
Ivan

Reputation: 8758

Basically there are two options depending on what type of autowiring can use. If you can use (or easily change your code to use) constructor autowiring then you could do the following:

@Autowired
public YourBean(@Value("${my.path.to.file}") String path) {
  if (resourceExists) { //your check here
    res = Optional.of(yourExistingResource);
  } else {
    res = Optional.empty();
  }
}

Second option is to use @PostConstruct annotation

@Value("${my.path.to.file}")
private String resourceName;
private Optional<Resoucre> res;

@PostConstruct
private void init() {
  //check that resource exists. At this time all dependencies are already injected.
  if (exists) {
    //init yourResoucre if it is not initialized earlier
    res = Optional.of(yourResource);
  } else {
    res = Optional.empty();
  }
}

I would prefer constructor injection

Upvotes: 1

Related Questions