Monday, May 13, 2013

inject a value in a static field using spring

I don't know any software developer who's a great fan of legacy code but as any developer I know that there's no escape from it too. There's a utility class that is used everywhere in our project. I'd like to inject two arguments in it and then use them in another method. But every method of this class is static and Spring does not like injecting stuff in static classes. One way to do it is to add a bean definition for this static class (as if this is not a utility class but a singleton class) and inject the variables. But a better way is to use static method call using MethodInvokingFactoryBean of Spring.

Our bean definition in the application context will be like this: 


We don't touch the class part. It should be "MethodInvokingFactoryBean". We will give two properties. The "staticMethod" property will tell Spring the class and its method where we will inject the arguments. The second property (arguments) will tell Spring which arguments to be injected. I'm injecting a list of arguments here. The list consists of "apology" and "accepted". I have my bean definition but where's my class? Here it is:
public class ExampleUtil {
 private static String argument1, argument2;
 public static void setArguments(String arg1, String arg2){
  argument1 = arg1;
  argument2 = arg2;

 public static void printArguments(){
  System.out.println("args: "+argument1+", "+argument2);

If you debug you'll try that two Strings (apology and accepted) is injected to ExampleUtil's setArguments() method. As they are static fields they can be reached from other methods such as printArguments().

No comments:

Post a Comment