我可以告诉spring只有在资源文件确实存在的情况下才注入(inject)资源吗?因为对于以下内容,如果定义了属性 my.path.to.file
,则 res.isPresent()
始终为真。但我只希望它在背后的资源确实存在的情况下为真。
@Value("${my.path.to.file}")
private Optional<Resource> res;
最佳答案
根据可以使用的 Autowiring 类型,基本上有两种选择。 如果您可以使用(或轻松更改您的代码以使用)构造函数 Autowiring ,那么您可以执行以下操作:
@Autowired
public YourBean(@Value("${my.path.to.file}") String path) {
if (resourceExists) { //your check here
res = Optional.of(yourExistingResource);
} else {
res = Optional.empty();
}
}
第二种选择是使用@PostConstruct
注解
@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();
}
}
我更喜欢构造函数注入(inject)
关于java - 仅当文件存在时如何注入(inject) Optional<Resource>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51610334/