Spring and Helper classes

If you use helper classes and Spring injection it might happen you need to inject beans into static fields of your helper classes.

In this case it can come handy a Spring class called org.springframework.beans.factory.config.MethodInvokingFactoryBean.

Consider the following two classes where Static represents your helper class and NonStatic your injected bean:

package org.agileware.example;

import org.springframework.stereotype.Service;

@Service
public class Static {

	private static NonStatic injected;

	public static void setInjected(NonStatic injected) {
		Static.injected = injected;
	}

	public static final void test() {
		if (injected == null) {
			throw new RuntimeException();
		}
	}
}

package org.agileware.example;

import org.springframework.stereotype.Component;

@Component
public class NonStatic {

	public NonStatic() {
		super();
	}
}

You can inject a NonStatic instance into the Static class by invoking the static method using the following XML Spring configuration snippet:

  <bean id="nonStatic" class="org.agileware.example.NonStatic"/>
  <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="org.agileware.example.Static.setInjected"/>
    <property name="arguments">
      <list>
        <ref bean="nonStatic"/>
      </list>
    </property>
  </bean>