简体   繁体   English

Java枚举和管理状态

[英]Java Enum and managing state

I want to use and Enumeration type to represent feature flags in my application. 我想使用和枚举类型来表示应用程序中的功能标志。 The enumeration type has a state and a description. 枚举类型具有状态和描述。 I want to be able do something like the following in my code; 我希望能够在我的代码中执行以下操作;

FeatureFlag.FANCYFEATURE.isActive()

The isActive() method would then call out to a service class connecting to a database to fetch the features state. 然后,isActive()方法将调出连接到数据库的服务类以获取功能状态。

However in my spring application its not possible inject a bean into an Enum as the Enum type is static. 但是在我的spring应用程序中,因为Enum类型是静态的,所以不可能将bean注入Enum中。

Can someone recommend a clean way to so this? 有人可以推荐一种干净的方法吗?

The following statement should tell you something is wrong 以下语句应告诉您有什么问题

The isActive() method would then call out to a service class connecting to a database to fetch the features state 然后,isActive()方法将调出连接到数据库的服务类以获取功能状态

If you are fetching the state, we can assume it might be different at different times, ie. 如果您要获取状态,我们可以假设它在不同的时间可能不同。 not a constant. 不是一个常数。 Don't use enum for this. 不要为此使用enum

And if you did, to answer 如果你做了,就回答

Can someone recommend a clean way to so this? 有人可以推荐一种干净的方法吗?

There is no way to inject beans into it, like you said. 就像您说的那样,没有办法将豆子注入其中。

By all means use an enum for a list of features but please don't use the enum for mutable state. 一定enum用于功能列表,但请不要将enum用于可变状态。

You would be better off using a EnumMap<Enum,State> structure to store mutable state against an enum . 使用EnumMap<Enum,State>结构存储对enum可变状态会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM