Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use @Autowired with static fields?

People also ask

Can static fields be Autowired?

In short, no. You cannot autowire or manually wire static fields in Spring.

Can we inject a Spring bean as static?

You have no choice. If you want to initialize a static field of a class, you will have to let Spring create an instance of that class and inject the value.

Does Autowire work with private fields?

The Spring Framework does allow you to autowire private fields. You do see people doing this. And Spring will perform some reflection magic to perform dependency injection.


In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.


@Component("NewClass")
public class NewClass{
    private static SomeThing someThing;

    @Autowired
    public void setSomeThing(SomeThing someThing){
        NewClass.someThing = someThing;
    }
}

@Autowired can be used with setters so you could have a setter modifying an static field.

Just one final suggestion... DON'T


Init your autowired component in @PostConstruct method

@Component
public class TestClass {
   private static AutowiredTypeComponent component;

   @Autowired
   private AutowiredTypeComponent autowiredComponent;

   @PostConstruct
   private void init() {
      component = this.autowiredComponent;
   }

   public static void testMethod() {
      component.callTestMethod();
   }
}

Create a bean which you can autowire which will initialize the static variable as a side effect.


You can achieve this using XML notation and the MethodInvokingFactoryBean. For an example look here.

private static StaticBean staticBean;

public void setStaticBean(StaticBean staticBean) {
   StaticBean.staticBean = staticBean;
}

You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.

Note testing can also be more difficult with this approach.


Wanted to add to answers that auto wiring static field (or constant) will be ignored, but also won't create any error:

@Autowired
private static String staticField = "staticValue";