Julie Langstrump
Julie Langstrump

Reputation: 897

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?

Upvotes: 1

Views: 3369

Answers (3)

DwB
DwB

Reputation: 38328

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

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160291

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.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340963

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.

Upvotes: 3

Related Questions