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

@Component
public class Foo
{

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

@Autowired
ObjectA autowiredObjectA; // Orginal bean that is autowired

@postConstruct
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.. !!

Comments

  1. And how do you write the unit test. Can you show some example.

    ReplyDelete

Post a Comment

Popular posts from this blog

'jasypt.encryptor.password' or one of ['jasypt.encryptor.privateKeyString', 'jasypt.encryptor.privateKeyLocation'] must be provided for Password-based or Asymmetric encryption

Field or property 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - Spring Batch

java.security.spec.InvalidKeySpecException: Only RSAPrivate(Crt)KeySpec and PKCS8EncodedKeySpec supported for RSA private keys