代码之家  ›  专栏  ›  技术社区  ›  Serg046

spring@value()的默认值异常

  •  -3
  • Serg046  · 技术社区  · 6 年前

    我是java/spring新手。我需要从CONFIG中读取一些值,但是如果它不存在,它应该失败。现在我有以下代码:

    public class SomeClass {
    
        @Value("${some.property:#{null}}")
        private String someProperty;
    
        public void someMethod() throws Exception {
            if (someProperty == null) throw new AopConfigException("The property must be set");
        }
    
    }
    

    很好,但我需要补充 if 封锁。我能写些那样的东西吗?

    @Value("${some.property:#{throw new AopConfigException(\"The property must be set\")}}")
    private String someProperty;
    

    @Value("${some.property:#{throwException()}}")
    private String someProperty;
    
    private static void throwException() {
        throw new AopConfigException("The property must be set");
    }
    

    立即失败

    升级版: 如果我不使用下面建议的默认值,那么它对我来说仍然不会失败。我没有 java.lang.IllegalArgumentException 以下内容:

    enter image description here

    5 回复  |  直到 6 年前
        1
  •  1
  •   dpr    6 年前

    为了使财产置换工作,您需要添加 PropertySourcesPlaceholderConfigurer bean到您的配置,如下所示( example taken from here )以下内容:

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties(){
      final PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
      // add your property files below
      final Resource[] resources = new ClassPathResource[]{new ClassPathResource("foo.properties")};
      pspc.setLocations( resources );
      // this will make the replacement fail, if property is not known
      pspc.setIgnoreUnresolvablePlaceholders(false); 
      return pspc;
    }
    

    如果已使用配置属性源 @PropertySource 注释您应该能够省略将资源添加到 属性资源占位符配置程序 手动,因为它应该自动从弹簧环境中拾取值。

    一旦这个bean就位,只需使用

    @Value("${data.import.path}")
    

    如果没有默认值(如其他答案中所述),应用程序的初始化将在很早的阶段失败。

        2
  •  5
  •   Yogen Rai    6 年前

    @默认情况下,值是必需的。所以,就用

    @Value("${some.property}")
    

    而不是

    @Value("${some.property:#{null}}")
    

    因此,如果该属性不存在,则应用程序无法从这样的异常开始:

    Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'invalid.value' in value "${invalid.value}"
    

    更新: 如果您想要一个密钥,并且该密钥可以是空的,则如下所示:

    some.property=
    

    如果该属性为空,则要引发异常,然后使用 @PostConstruct 如下所示:

        @PostConstruct
        public void validateValue() {
            if (someProperty.isEmpty()) {
                throw new MyNiceException("error");
            }
        }
    

    更多更新: 如果您希望在没有注册表项的情况下初始化null

        @Value("${some.property:#{null}}")
        private String someProperty;
    

    然后这样做:

            @PostConstruct
            public void validateValue() {
                if (someProperty == null) {
                    throw new IllegalArgumentException("error");
                }
            }
    
        3
  •  1
  •   elisman    6 年前

    恐怕你不能只用 @Value 注解。但是,可以通过使用spring环境读取值来检查是否设置了某个属性。这会导致 IllegalStateException 如果未设置该值。

    例如,如果您有环境变量,例如:

    @Autowired
    private ConfigurableEnvironment env;
    

    然后可以通过调用方法初始化该值 getRequiredProperty 以下内容:

    <T> T getRequiredProperty(java.lang.String key, java.lang.Class<T> targetType) 
          throws java.lang.IllegalStateException
    

    因此,对于您的用例,您可以这样初始化bean:

    @Bean
    public SomeClass someClass () {
    
      String someProperty = env.getRequiredProperty ("some.property");
    
      return new SomeClass (someProperty);
    }
    
        4
  •  0
  •   diginoise    6 年前

    只需在post construct中进行验证,以确保在创建bean后立即运行它:

    @PostConstruct
    private static void throwException() {
      if (someProperty == null) {
        throw new AopConfigException("The property must be set");
      }
    }
    
        5
  •  0
  •   recursion    6 年前

    请不要将默认值设置为 @Value("${some.property}")

    如果属性没有设置,那么spring将通过一个异常完成,并且您做得很好。