Here is a reason why spring cannot inject static variables. The specific details are as follows:
Spring dependency injection is a dependency set method
Set method is a normal object method
Static variables are attributes of classes
@Autowired private static JdbcTemplate jdbcTemplate;
Just looking at this injection process, there is no error, but the next jdbcTemplate.query() will report a null pointer error.
ps: Spring injects static variables
Today I encountered a problem. One of my tool classes provides several static methods. The static methods require another class instance to provide processing, so I wrote this code:
Class Util{ private static XXX xxx; xxx = BeanUtil.getBean("xxx"); public static void method(){ xxx.func(); } public static void method(){ xxx.func(); } }Here is the way to use getBean to get XXX instance, but others say that this method is not good and want to inject it.
But how to inject static XXX?
I searched many statements online, but it was actually very simple:
Class Util{ private static XXX xxx; public void setXxx(XXX xxx){ this.xxx = xxx; } public void getXxx(){ return xxx; } public static void method1(){ xxx.func1(); } public static void method2(){ xxx.func2(); } }Just configure the injection in XML normally.
<bean value="test"> <property value="xxx" ref="xxx"/></bean>
Note here that the automatically generated getter and setter methods will have static qualifiers and need to be removed before they can be done.