当资源不存在时,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));
        }

    }