Jump to content

Spring and bean dependancy injection available for static methods.

- - - - -

  • Please log in to reply
1 reply to this topic

#1
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Okay, here's my problem.
Spring allows users to dependancy inject / autowire beans into objects, essentially by doing.

public class Something{

  @Autowired

  private InjectMe injectMe

}

And upon creating a new instance of this class, Spring makes sure that injectMe gets filled with the current bean if present, or a new instance if not.

Useful for injecting DAOs in your DAL and various other places where it's useful.

Problem is, I need this autowired object inside a static method. Meaning to object gets created, and Spring.. as far as I know does not autowire static fields.


public class Something{

  @Autowired

  private static InjectMe injectMe


  public static useInjectMe(){

    injectMe.foo();

  }

}

^ That's what I want.

v This is what's the current workaround:

public class Something{

  @Autowired

  private InjectMe injectMe


  public static useInjectMe(){

    new Someting().injectMe.foo();

  }

}

Which looks awful, and there's got to be a better way.

Anyone ever been in this situation before?

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Ha ha, here's the verbose way:
public class Something

{

    private class InternalData {

        @Autowired

        InjectMe injectMe

    }

    private static InternalData data = new InternalData();


    public static useInjectMe()

    {

        data.injectMe.foo();

    }

}
I don't use the Spring framework, so I only superficially understand the @Autowired annotations functionality. I'm just not sure what you mean by "there's got to be a better way," since what better means isn't defined. Shortest is pretty much what you've done, only issue is you're creating a new Something each time, and mine just makes one object. So yeah, depends on what is meant by better.

Edited by ZekeDragon, 06 May 2011 - 08:57 PM.

Wow I changed my sig!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users