英文:
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.A
或MyEnum.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 {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论