Spring static variable dependency injection example

In Spring framework, injecting values for static variable or field direct approach is not useful. In the all previous example, we have used <property/> tag for setter-based dependency injection but if you have static variable or field and static method in your bean then we need to inject it by invoking the MethodInvokingFactoryBean class.

MethodInvokingFactoryBean class have two method setStaticMethod(String staticMethod) and setArguments(Object[] arguments), we can inject value through these method.

1- setStaticMethod(String staticMethod)- In the <property/> tag set the staticMethod to the name attribute and qualified path of static setter method to the value attribute.

<property name="staticMethod" value="org.websparrow.beans.Employee.setEmpName" />

2- setArguments(Object[] arguments)- It is used for setting the values. Set the arguments to the name attribute of <property/> tag and actually it is Array of object so used the <list/> tag to inject the value.

<property name="arguments">
        <value>Sandeep Sharma</value>

Technologies Used: Spring 5.0.4.RELEASE | JDK 8 | Eclipse Mars 2

Let’s see the complete example.

Spring Beans

Create the beans which contains static variable and method.

package org.websparrow.beans;

public class Employee {

	public static String empName;

	public static void setEmpName(String empName) {
		Employee.empName = empName;

	public static void display() {
		System.out.println("Employee name is: " + empName);

Spring Beans Configuration

For injection value to the static variable, create the object of MethodInvokingFactoryBean class and set static method and argument name as discussed above.

<?xml version="1.0" encoding="UTF-8"?>

	<bean id="emp" class="org.websparrow.beans.Employee" />

	<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
		<property name="staticMethod" value="org.websparrow.beans.Employee.setEmpName" />
		<property name="arguments">
				<value>Sandeep Sharma</value>

Run it

Load the configuration file and run it.

package org.websparrow.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.websparrow.beans.Employee;

public class Client {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
		Employee emp = (Employee) context.getBean("emp");


You will get the following result on the console log.

Employee name is: Sandeep Sharma

Note: If you are using Spring 5 then simply inject the values using <property/> tag, no need to invoke the MethodInvokingFactoryBean class. Spring will take care of it.

Share this article on: