Spring injects static member variables

Source: Internet
Author: User

Problems encountered in the work, in the tool class need to inject the static member variable value, and static member variables are loaded at the time of the class loading, so has been reported null pointer.

On the internet to find a few ways to record.

The first: Use the SET function injection.

 1   @Component  2  public   Class   Logutil { 3  4  private  static   Paylogdao Logdao;  5   @Autowired  6  public   void   Setlogdao (Paylogdao Logdao) { 7  Logutil.logdao = Logdao;  8  }  9  }

The second type: Use @PostConstructy annotations.

1 @Component2  Public classLogutil {3 @Autowired4     PrivatePaylogdao Logdao;5 6     Private StaticLogutil Logutil;7 8 @PostConstruct9     Private voidinit () {TenLogutil = This; One     } A  -      Public  Static voidWritesuccesslog (String ip,string mac,string clazz,string msg) { -Paylog log =NewPaylog (); the Log.setlogid (Idutil.getid ()); - LOG.SETLOGIP (IP); - Log.setlogmac (MAC); - log.setlogmsg (msg); + Log.setlogclass (clazz); - Log.setlogtime (Dateutil.getnowtime ()); +         Try{ A logUtil.logDao.writeLog (log); at}Catch(Exception e) { -             //catch exceptions, do not block business -         } -     } -}

The first one has not been tried, I use the second kind.

  

  

  

Spring injects static member variables

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.