Sunday, 13 January 2013

Spring Dependency Injection into Static (Class) Variables

Shouldn't do it, as it can cause threading issues and unexpected behaviour due to global state, but it is possible.

First define the class we want to inject
public class Dao{  
  public String getMessage()
    return "Hello world"; 
Now define the class which will use the dao class above.
public class HelperClass{

  private static Dao sDao; //class variable to point to dao

  // class level getter method
  public static Dao getDao(){ return sDao; }

  //Instance setter method, for spring injection
  public void setDao(Dao aDao)
    sDao = aDao; //store reference in class var

How It Works

Spring will create an instance of the Dao class and store it in the repository. It will then try creating an instance of the HelperClass. When it comes across the @Autowired on the setDao(..) method, it will retrieve the Dao instance from the repository and pass it in as the first argument for the method. Inside the setDao(..) method we get the injected Dao reference and store it at the class level.


Now we can use the Dao anywhere in our code. Even in classes not managed by spring, for example when creating an object with the forbidden new keyword.
class Printer{
  public void printMessage()

Printer printer = new Printer();

printer.printMessage(); //will print 'Hello world'

No comments:

Post a Comment