有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java@ConfigurationProperties和不可解析属性

假设以下配置bean:

@ConfigurationProperties(prefix="foo")
private class FooProperties {
   private String mystring;
   private int myint;
}

以及以下{}:

foo.mystring = ${bar.mystring}
foo.myint    = ${bar.myint}

请注意,这两个属性是不可解析的,因为没有定义以bar开头的属性。以下是将会发生的情况:

  • foo.mystring设置为字符串"${bar.mystring}"(无解析)
  • foo.myint将导致转换错误,因为无法将字符串"${bar.myint}"转换为有效整数

相反,我希望在这种情况下抛出一种不可解析属性异常。就像我使用@Value("${foo.mystring}")会发生什么一样

这种行为是预期的吗? 在这种情况下,有没有办法让SpringBoot抛出这样的异常


共 (1) 个答案

  1. # 1 楼答案

    I would instead expect a kind of Unresolvable Property exception being thrown in this case.

    foo.myint并没有抛出Unresolvable Property exception,因为它是通过${bar.myint}解决的,而当Spring尝试将String类型转换为int时,它在下一步失败的,因为存储在Properties文件中的每一样东西都是字符串值,除非您明确指定它的类型,如下所示:

    foo.myint = (java.lang.Integer)${bar.myint}
    

    Is that behaviour expected?

    可能是的

    Is there a way to make SpringBoot throw such exception in this case?

    是的,对于Global级别,您可以使用@ControllerAdvice,如果您想在Controller级别使用它,那么您可以使用@ExceptionHandler