Wednesday, January 2, 2019

Can you use @Autowired with static fields?

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


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

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

Using constroctor over to static field:

 
@Component
public 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:

@Component
public class Boo {

    private static Foo foo;
    @Autowired
    private Foo tFoo;

    @PostConstruct
    public void init() {
        Boo.foo = tFoo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}

 

  

No comments:

Post a Comment

Spring Annotations