Reputation: 850
I need to hide some menu options in the production environment, but not in development.
I implemented this as an enum like this:
public enum Functionality {
FUNCTION_1(true),
FUNCTION_2,
FUNCTION_3(true);
private boolean usable;
Functionality() {
this(false);
}
Functionality(boolean usable) {
this.usable = usable;
}
public boolean isUsable() {
return usable;
}
}
And then, when I need to show the menu options, I check whether that functionality needs to be shown.
So I need to be able to change the usable boolean when the environment is development. But I cannot find any way to do it in Spring.
Do you know of a way to do something like this?
Upvotes: 1
Views: 1663
Reputation: 308141
You could change the fields of an enum
, but it's usually considered a bad idea and is often a design smell.
A better approach would possibly be to not have usable
be a field at all, instead make it a calculated property:
public enum Functionality {
FUNCTION_1(true),
FUNCTION_2,
FUNCTION_3(true);
private final boolean restricted;
Functionality() {
this(false);
}
Functionality(boolean restricted) {
this.restricted = restricted;
}
public boolean isRestricted() {
return restricted;
}
public boolean isUsable() {
if (!restricted) {
return true;
} else {
return SystemConfiguration.isDevelopmentSystem();
}
}
}
Obviously there would need to be a method like SystemConfiguration.isDevelopmentSystem()
for this to work.
In some systems I implemented I used another enum
for this:
public enum SystemType {
PRODUCTION,
TESTING,
DEVELOPMENT;
public final SystemType CURRENT;
static {
String type = System.getEnv("system.type");
if ("PROD".equals(type)) {
CURRENT = PRODUCTION;
} else if ("TEST".equals(type)) {
CURRENT = TESTING;
} else {
CURRENT = DEVELOPMENT;
}
}
}
Here I used a system property to specify the type at runtime, but any other configuration type might be just as appropriate.
Upvotes: 2
Reputation: 3975
java enums are singleton and immutable, so I dont think you can change enum state anyway.
Upvotes: -1
Reputation: 3549
enums are essentially constants. With the hard-coding of true
to FUNCTION_1
and FUNCTION_3
, there isn't a way that Spring can inject anything.
This is a duplicate of: Using Spring IoC to set up enum values
Upvotes: 0