Why Spring cannot inject Static variables and why Spring cannot inject Static variables

  • 2020-04-01 04:34:00
  • OfStack

Here's why spring can't inject a static variable:

Spring dependency injection is a set method

A set method is a normal object method

A static variable is an attribute of a class


 @Autowired 
 private static JdbcTemplate jdbcTemplate;

There are no errors in the injection process alone, but the following jdbctemplate.query () reports a null pointer error.

Ps: Spring injects static variables

Today, I encountered a problem. One of my utility classes provided several static methods, which required another instance of the class to provide processing, so I wrote the following 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 getBean is used to get an instance of XXX, but others say this method is bad and want to inject it.

But how do you inject static XXX?

The Internet looked up a lot of terms, in fact, it is 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 normally in the XML.


<bean value="test" class="x.x.x.Util">
  <property value="xxx" ref="xxx"/>
</bean>

Notice that the getter and setter methods that are automatically generated are going to have a static qualifier that needs to be removed.


Related articles: