无法在 @ConditionalOnProperty 的 havingValue 上使用枚举。

huangapple go评论62阅读模式
英文:

Can't use enumration on @ConditionalOnProperty havingValue

问题

以下代码将无法编译,我会得到“属性值必须是常量”的错误。

是否有解决方法使其工作?

@Service
@ConditionalOnProperty(name = "my.property", havingValue = MyEnum.A.name())
public class MyService {
}
public enum MyEnum {
    A,
    B
}
英文:

Following code won't compile, I get "Attribute value must be constant".

Is there a workaround to get it working?

@Service
@ConditionalOnProperty(name = "my.property", havingValue = MyEnum.A.name())
public class MyService {
}
public enum MyEnum {
    A,
    B
}

答案1

得分: 1

不幸的是,您不能使用@ConditionalOnProperty或像示例中的链接中所示的自定义Conditional类/注解来执行此操作。

您不能使用havingValue发送MyEnum.AMyEnum.A.name(),因为编译时常量只能是原始类型和字符串。

您可以使用**@ConditionalOnProperty**进行比较:

@Service
@ConditionalOnProperty(
        name = "my.property", havingValue = "A"
)
public class MyService {}

或者,您可以使用**@ConditionalOnExpression**进行比较:

@Service
@ConditionalOnExpression(
        value = "#{T(com._75471475.MyEnum).valueOf('${my.property}') == T(com._75471475.MyEnum).A}"
)
public class MyService {}
英文:

Unfortunately you cannot do this with @ConditionalOnProperty or with a custom Conditional class / annotation like in the example in this link.

You can't send MyEnum.A or MyEnum.A.name() with havingValue, because compile constants can only be primitives and Strings.

You can do the comparison with @ConditionalOnProperty:
@Service
@ConditionalOnProperty(
        name = "my.property", havingValue = "A"
)
public class MyService {}
Alternatively you can do the comparison with @ConditionalOnExpression:
@Service
@ConditionalOnExpression(
        value = "#{T(com._75471475.MyEnum).valueOf(\'${my.property}\') == T(com._75471475.MyEnum).A}"
)
public class MyService {}

huangapple
  • 本文由 发表于 2023年2月16日 19:16:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定