• Now all data be ready for publish, We had made our blog alive now. Haha.

  • These days CCP GFW blocked all the IPs from US and when I switch my IP in google Cloud, the disk data cannot be restore again. I have to restart my blog totally, Now the website is still building…

How to make spring inject value into a static field- Stack Overflow

Java PingBook 2 months ago (10-23) 15 0


I know this may looks like a previously asked question but I’m facing a different problem here.

I have a utility class that has only static methods. I don’t and I won’t take an instance from it.

public class Utils{
private static Properties dataBaseAttr;
public static void methodA(){


public static void methodB(){


Now I need Spring to fill dataBaseAttr with database attributes Properties.Spring config is:

I already done it in other beans but the problem here in this class (Utils) isn’t a bean, And if I make it a bean nothing changes I still can’t use the variable since the class will not be instantiated and variable always equals null.


You have two possibilities:

non-static setter for static property/field;
using org.springframework.beans.factory.config.MethodInvokingFactoryBean to invoke a static setter.

In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.

public void setTheProperty(Object value) {
foo.bar.Class.STATIC_VALUE = value;

but in order to do this you need to have an instance of a bean that will expose this setter (its more like an workaround).

In the second case it would be done as follows:

On you case you will add a new setter on the Utils class:

public static setDataBaseAttr(Properties p)

and in your context you will configure it with the approach exemplified above, more or less like:

Copyright from PingBook Blog, If not specified, they are original. This site uses BY-NC-SAProtocol authenticated.
For reprinting, please indicate the link of the original text:How to make spring inject value into a static field- Stack Overflow
LIKE (0)
We create, We sharing! Tag every value data your sharing
Submit comments
Cancel comments
emoji picture bold strikethrough center italic check in

Hi,you need to provide your name and email adress!

  • Name (Required)
  • Email (Required)
  • Website