简体   繁体   English

如何在Spring中从上下文设置静态最终参数?

[英]How to set static final parameter from context in Spring?

I have Class with static final fields and I want to initialize them from my context..Can I do this? 我有静态最终字段的类,我想从我的上下文中初始化它们。我可以这样做吗? Or I have to look for another solution? 或者我必须寻找另一种解决方案?

Since final variables are effectively constants that have to be defined exactly once during initialization, you cannot do this with Spring (or with Java in general). 由于final变量是在初始化期间必须完全定义一次的有效常量,因此无法使用Spring(或通常使用Java)执行此操作。 However look at: Java 5 - "final" is not final anymore . 但是请看: Java 5-“最终”不再是最终的

It's final , how'd that work? 这是final ,那是怎么回事?

You can assign to a non - final static variable by providing a normal setter using non-reflective Java. 您可以通过使用非反射Java提供普通的setter来分配给 final静态变量。 You may be able to use reflection as noted by Tomasz to set the final field. 您可能可以使用Tomasz指出的反射来设置最终字段。

Based on the comment by "matt b" you can remove the final from the variable declaration and implement "set once" functionality in the setter. 根据“matt b”的注释,您可以从变量声明中删除final,并在setter中实现“set once”功能。

For example: 例如:

private static String blammy = null;

public String getBlammy() { return blammy; }

public void setBlammy(String newValue)
{
  if (StringUtils.isNotBlank(newValue)) // only set to a non blank value.
  {
    if (blammy == null) // set once functionality
    {
      blammy = newValue;
    }
  }
}

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

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