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;

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;

public class NonStatic {

	public NonStatic() {

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">
        <ref bean="nonStatic"/>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s