开发者

How do I change the property of an enum with Spring?

开发者 https://www.devze.com 2023-03-04 05:57 出处:网络
I need to hide some menu options in the production environment, but not in development. I implemented this as an enum like this:

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 s开发者_C百科hown.

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?


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.


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


java enums are singleton and immutable, so I dont think you can change enum state anyway.

0

精彩评论

暂无评论...
验证码 换一张
取 消