Spring — Static variable Dependency Injection | Code Factory

Spring Tutorial Index Page: Link

  • To inject static variable normal way of declaring <bean> is not useful.
  • By using MethodInvokingFactoryBean class we pass static variable vallues.
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" />
  • MethodInvokingFactoryBean have 2 methods
    - setArguments(Object[] arguments)
    - setStaticMethod(String staticMethod)

Create Java Project

  • Open Eclipse
  • Go to File -> New -> Others… -> Java Project
  • Create DI-StaticVariable project
  • Right click on project -> Build Path -> Configure Build Path -> Libraries tab -> Add External JARs
    - commons-logging-X.X.jar
    - spring-beans-X.X.X.jar
    - spring-context-X.X.X.jar
    - spring-core-X.X.X.jar
  • * You can find dtd information from spring-beans-X.X.X.jar -> org -> springframework -> beans -> factory -> xml -> spring-beans.dtd (line no 36 & 37)
<bean id="c" class="com.codeFactory.beans.Car" />

<!-- static variable DI -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" >
<property name="staticMethod" value="com.codeFactory.beans.Car.setCompanyName" />
<property name="arguments">
package com.codeFactory.beans;/**
* @author code.factory
public class Car {
private static String companyName;
public static void setCompanyName(String companyName) {
Car.companyName = companyName;
public static void print() {
System.out.println("Company Name " + companyName);
package com.codeFactory.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codeFactory.beans.Car;/**
* @author code.factory
public class Client {
public static void main(String... args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/codeFactory/resources/spring.xml");
Car t = (Car) context.getBean("c");
Company Name JLR




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Mobile development suite: How to use Termux + my setup

The Best Debugging Technique Doesn’t Use A Computer

Python: smart coding with locals() and global()

Top React Jobs — Week 42, 2021

React.js Jobs

Top 3 Coding Languages

Superior Asura Hosting: Things other costly Hosting Providers don’t want you to know 2021

Integration Testing

The fastest template engine for PHP

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Visitor Design Pattern in Java

Field Injection v/s Constructor Injection

Experience with Spring batch and docker

Java extension mechanism — Self discovery & bean instantiation