Spring — Static variable Dependency Injection | Code Factory
2 min readJan 21, 2021
Donate : Link
WordPress Blog : Link
Applications… : Link
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)
spring.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd"><beans>
<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">
<list>
<value>JLR</value>
</list>
</property>
</bean>
</beans>
Car.java
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);
}
}
Client.java
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");
t.print();
}
}
Output:
Company Name JLR