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:
- @Component//Declaration as Spring component
- Public class Testutils {
- @Autowired
- private Testservice Testservice; Add a private member of the required service
- 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
- public void Settestservice (Testservice testservice) {
- this.testservice = Testservice;
- }
- @PostConstruct//Key two operations performed prior to initializing and destroying beans through @postconstruct and @PreDestroy methods
- public void init () {
- Testutils = this ;
- Testutils.testservice = This.testservice; Instantiate a static testservice at the beginning of the initialization
- }
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