Wednesday, August 26, 2015

Autowiring a static variable using Spring

Yes, This sounds wrong and should never try to do it in a proper design (According to me).

With the above disclaimer, Might run into such a case where we need to do this kind of thing, you are at the right blog.

There are 2 ways to do it i guess, i have the simple working way jotted here.

Lets get started

Consider the class

public class Foo

private static ObjectA objectA; // Static variable to be used in static method in class

ObjectA autowiredObjectA; // Orginal bean that is autowired

public void init()

  Foo.objectA=this.autowiredObjectA; // So this method is responsible for handing out the bean after                                                                     the class is constructed and autowired by the spring                                                                                  container . :)


public static consumerMethod(args..)
  objectA.makeCall(); // making a call with the static auto wired object



Now the above snippet will do the trick.

1. Spring does a component scan and load the class.
2. container auto wires the bean.
3. container calls the post construct where bean is assigned to static variable.
4. the static variable is used during function calls.

If there is a proper design, i guess this kind of situation can be avoided for every other case.. !!

No comments:

Post a Comment