Spring injection Service NULL alternative Workaround tool class general class static non-controller

Source: Internet
Author: User

The system is the SPRINGMVC framework, where some tool classes need to invoke the service layer managed by spring under the development process. But the injection does not come in, the null exception is reported;

After trying out a series of methods on the Internet, there is still no solution. There are several main solutions on the Internet:

1, the tool class is declared as spring components, such as @controller @compent, etc., in the Spring Auto-scan package settings will be included in the package of the tool class; invalid

2, new a service, invalid and not in line with spring management;

After the dead, found an alternative solution, the code principle is not very clear, but probably guess under, there is the wrong place, we leave a message:

  1. @Component//Declaration as Spring component
  2. Public class Testutils {
  3. @Autowired
  4. private Testservice Testservice; Add a private member of the required service
  5. private static testutils testutils; Key point 1 static initial enable a tool class so that it is in order to be before the beginning of spring
  6. public void Settestservice (Testservice testservice) {
  7. this.testservice = Testservice;
  8. }
  9. @PostConstruct//Key two operations performed prior to initializing and destroying beans through @postconstruct and @PreDestroy methods
  10. public void init () {
  11. Testutils = this ;
  12. Testutils.testservice = This.testservice; Instantiate a static testservice at the beginning of the initialization
  13. }

This allows the service processing to be invoked through Testutils.testservice in the following code

Spring injection Service NULL alternative Workaround tool class general class static non-controller

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.