Why spring cannot inject static variables and the spring injection statically variable _java

Source: Internet
Author: User

Here's why spring can't inject static variables, as detailed below:

Spring Dependency Injection is dependent on the Set method

The set method is a normal object method

A static variable is a property of a class

 @Autowired 
 private static JdbcTemplate JdbcTemplate;

There is no error in the injection process, but the next jdbctemplate.query () will report null pointer errors.

ps:spring injection of static variables

Today, I have a problem where one of my tool classes provides several static methods, and the static method requires an instance of another class to provide the processing, so this code is written:

 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 an example of xxx, but others say this method is not good and want to inject the way.

  But how is static xxx injected?

Online Search a lot of statements, in fact 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 ();
  }   
}

Normal configuration of injection in XML is OK.

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

Note here that the automatically generated getter and setter methods come with a static qualifier that needs to be removed before it can be used.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.