简体   繁体   中英

Assigning private static final field member using spring injection

Is it possible to achieve such an assignment. The article here deals with private static field members but it does not help in this case as final members cannot be assigned.

Justification for using private static final as a qualifier for the member:

  • The data member is a ServiceClient so it makes sense to have it attached to type as it does not depend on the instance. Its thread safe too, so it will improve performance as I will not initialize the client for each instance.
  • The service client itself is a bean, having singleton scope. Hence actually there is only one instance. Since there will always be one instance, there is no point in allowing reassignment.
  • Since this client is only be used by methods of this class, it is private.

I am not exactly sure if this is an anti-pattern, but if it is then do my justification qualify to use it? If yes, then how can it be done. If no, then please suggest an alternative (and I would still be interested to know how can this be achieved, just for knowledge purposes).

What you are trying to do, is not at all possible.

The most fundamental reason is that Java replaces static final "variable" occurrences in the code with the actual values (since it's of course known at compile time). Check out this SO answer for more details.

Even if you don't use final , Spring still won't allow you to inject a value into the static variable directly. You would have to use a setter like:

@Value("${my.name}")
public void setPrivateName(String privateName) {
    Sample.name = privateName;
}  

Check out this SO answer for more.

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