Injecting static variable in Spring 4.2

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:

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

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");
        car.printCar();
    }
}

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??

Answer

  • 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.

Leave a Reply

Your email address will not be published. Required fields are marked *