@Autowired and static method @Autowired and static method java java

@Autowired and static method


You can do this by following one of the solutions:

Using constructor @Autowired

This approach will construct the bean requiring some beans as constructor parameters. Within the constructor code you set the static field with the value got as parameter for constructor execution. Sample:

@Componentpublic class Boo {    private static Foo foo;    @Autowired    public Boo(Foo foo) {        Boo.foo = foo;    }    public static void randomMethod() {         foo.doStuff();    }}

Using @PostConstruct to hand value over to static field

The idea here is to hand over a bean to a static field after bean is configured by spring.

@Componentpublic class Boo {    private static Foo foo;    @Autowired    private Foo tFoo;    @PostConstruct    public void init() {        Boo.foo = tFoo;    }    public static void randomMethod() {         foo.doStuff();    }}


You have to workaround this via static application context accessor approach:

@Componentpublic class StaticContextAccessor {    private static StaticContextAccessor instance;    @Autowired    private ApplicationContext applicationContext;    @PostConstruct    public void registerInstance() {        instance = this;    }    public static <T> T getBean(Class<T> clazz) {        return instance.applicationContext.getBean(clazz);    }}

Then you can access bean instances in a static manner.

public class Boo {    public static void randomMethod() {         StaticContextAccessor.getBean(Foo.class).doStuff();    }}


What you can do is @Autowired a setter method and have it set a new static field.

public class Boo {    @Autowired    Foo foo;    static Foo staticFoo;       @Autowired    public void setStaticFoo(Foo foo) {        Boo.staticFoo = foo;    }    public static void randomMethod() {         staticFoo.doStuff();    }}

When the bean gets processed, Spring will inject a Foo implementation instance into the instance field foo. It will then also inject the same Foo instance into the setStaticFoo() argument list, which will be used to set the static field.

This is a terrible workaround and will fail if you try to use randomMethod() before Spring has processed an instance of Boo.