Injecting static variable in Spring 4.2 Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Injecting static variable in Spring 4.2 without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I was just trying to test the injection of static variables in the Spring 4.2. As i was following a tutorial, in that Spring 2.0 was used. In that tutorial if it was done as follows:

public class Car {
    private static String carName;

    public static void setCarName(String carName) {
        Car.carName = carName;

    public static void printCar(){
        System.out.println("Car name is: " + carName);

And my xml file is:

    <bean id="c" class="beans.Car">
        <property name="carName" value="Audi"/>

And my class to test it is:

public class Client {
    public static void main(String[] args) {
        ApplicationContext ap= new ClassPathXmlApplicationContext("resources/spring.xml");
        Car car= (Car)ap.getBean("c");

The above code was throwing error when used with Spring 2.0(as shown in the tutorial I was following). But if I am trying the same code in Spring 4.2, it is not showing any error and the code is working fine. Why is the difference in behavior?? Does Spring make any changes in the newer version for injection of static variables? So my question is can we do the DI of static variables directly as shown above??


  • For your first question, according to a comment here (emphasis is mine):

The intention of ExtendedBeanInfo, introduced with SPR-8079 in v3.1.0.M2, was to support dependency injection against non-void returning write methods. However, it also inadvertently introduced support for injection against static setter methods.

SPR-8079 shows that this is supported since 3.1 M2

  • For your second question, yes you can do static dependency injection, but because Car is a spring managed bean, it’s a singleton, so no need to use static methods/field in your example.
We are here to answer your question about Injecting static variable in Spring 4.2 - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji