【问题标题】:@Value force startup validation@Value 强制启动验证
【发布时间】:2017-02-23 09:08:59
【问题描述】:

我有以下弹簧组件。我想找到一种更优雅的方式来注入配置值。

@Component
public class Clazz {

    @Value("${config.value.foo:#{null}}")
    public String foo;

    @PostConstruct
    public validateFoo() throws ConfigException {
        if (foo == null || "".equals(foo)) {
            throw new ConfigException("Please provide config");
        }
    }
}

我使用 yaml 配置。如果我不添加#{null},配置名称(config.value.foo)将被注入String。另外,如果配置为空或为空,我希望 spring boot 应用程序不启动。

是否有另一个注解会从 config 注入值并在该值未配置或为 null 时抛出异常?

编辑:

如 cmets @Value 中所述,默认行为是在缺少配置时抛出异常。我对此进行了测试,并在具有相同配置的新项目上进行了测试。如果我删除我得到的配置值:java.lang.IllegalArgumentException: Could not resolve placeholder 我想我不会因为我导入的一些库而得到异常。

【问题讨论】:

  • 如果@Value 无法解析,这已经是默认行为,它会爆炸。如果不是这种情况,您的设置中配置有问题。
  • @M.Deinum 它不会抛出任何异常。我正在使用 spring boot 和 yaml 配置。它只是注入配置名称
  • 那么您在配置中做了一些奇怪的事情,破坏了默认行为。
  • 如果您将 yaml 文件添加到问题中,它会有所帮助。 @M。 Deinum 是对的,它应该抛出异常并且无法启动。
  • @Sergio 你是对的。在一个新的 spring-boot 项目中测试了配置并且它可以工作,所以它一定是我的项目中的东西。我认为这可能是我正在使用的某个库。我将尝试一一添加它们,看看是什么触发了它。谢谢

标签: spring spring-boot springfox spring-ioc


【解决方案1】:

如果有如下代码可能会发生这种情况:

PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer();
c.setIgnoreUnresolvablePlaceholders(true);

我的项目中没有这样的代码所以我在setIgnoreUnresolvablePlaceholders添加了一个断点这个方法被称为:

"main@1" prio=5 tid=0x1 nid=NA runnable
  java.lang.Thread.State: RUNNABLE
      at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.setIgnoreUnresolvablePlaceholders(PlaceholderConfigurerSupport.java:178)
      at springfox.documentation.swagger.configuration.SwaggerCommonConfiguration.swaggerProperties(SwaggerCommonConfiguration.java:38)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethodAccessorImpl.java:-1)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

所以问题是由 springfox 触发的。我还从我的项目中禁用了招摇(删除@EnableSwagger2),然后@Value 按预期工作并在缺少配置时抛出异常

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2012-11-02
    • 2017-01-06
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多