简体   繁体   中英

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). However look at: Java 5 - "final" is not final anymore .

It's final , how'd that work?

You can assign to a non - final static variable by providing a normal setter using non-reflective Java. You may be able to use reflection as noted by Tomasz to set the final field.

Based on the comment by "matt b" you can remove the final from the variable declaration and implement "set once" functionality in the setter.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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