如何解决当资源不存在时,SpringBoot上有什么方法可以返回配置Bean?
我正在寻找相反的东西
@ConditionalOnResource(resources = "${spring.info.build.location:classpath:META-INF/build-info.properties}")
我想要类似@ConditionalOnMissingResource
...
有什么想法吗?
解决方法
也许有一个更短或更聪明的选择,但这对我有用。
装饰您的bean创建方法
@Conditional(BuildInfoResourceNotAvailableCondition.class)
并将此静态嵌套类添加到您的配置类:
static class BuildInfoResourceNotAvailableCondition extends SpringBootCondition {
private final ResourceLoader defaultResourceLoader = new DefaultResourceLoader();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,AnnotatedTypeMetadata metadata) {
ResourceLoader loader = context.getResourceLoader();
loader = (loader != null) ? loader : this.defaultResourceLoader;
Environment environment = context.getEnvironment();
String location = environment.getProperty("spring.info.build.location");
if (location == null) {
location = "classpath:META-INF/build-info.properties";
}
ConditionMessage.Builder message = ConditionMessage
.forCondition("BuildInfoResource");
if (!loader.getResource(location).exists()) {
return ConditionOutcome
.match(message.didNotFind("build info at").items(location));
}
return ConditionOutcome
.noMatch(message.found("build info at").items(location));
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。