2011-05-11 86 views
1

我需要在生产环境中隐藏一些菜单选项,但不在开发中。如何更改Spring的枚举属性?

我实现了这个像这样的枚举:

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; 
    } 
} 

然后,当我需要显示菜单选项,我检查该功能是否需要显示。

所以我需要能够改变可用布尔当环境是发展。但在春季我找不到任何方法。

你知道一种方式来做这样的事吗?

回答

2

可能更改enum的字段,但它通常被认为是一个坏主意,通常是一种设计气味。

更好的方法可能是没有usable是现场所有,而不是使之成为计算性能:

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(); 
     } 
    } 
} 

显然,将需要像SystemConfiguration.isDevelopmentSystem()这个工作的方法。

在一些系统中,我实现我用另一种enum此:

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; 
     } 
    } 
} 

在这里,我使用的系统属性来指定在运行时类型,但任何其他配置类型可能是一样合适。

-1

Java的枚举是单身的和不可改变的,所以我不认为你可以改变反正枚举状态。

+0

该语言中没有指定enum值必须是不可变的。这是一个很好的设计决策和普遍接受的最佳实践,但不是必需的。 – 2011-05-11 09:19:57

+0

你绝对可以改变一个枚举的状态。你只需要在上面的代码中添加一个setUsable方法。 – 2011-05-11 09:26:45

+0

@ Joachim Sauer&@Thijs Wouters:对于误会,抱歉,因为枚举是单例,所以最好让它不变。 – blob 2011-05-11 09:30:12