First, a servlet is a dynamic Web project that differs from a common Java project and is managed by the Web. XML main profile in a dynamic webpage project.
Spring can only manage the normal pojo, and there is no way to inject it directly, even though there is no problem with the way you inject and configure.
So how do we solve this problem? The solution is always more than the problem encountered, otherwise spring MVC How to do it? In fact, filter will also encounter similar problems.
Personal advice to use the fourth way
The first solution is:
The Init method in the servlet, or the non-parametric construction method, is injected directly in the most primitive way, which is similar to the following:
Webapplicationcontext wactx = Webapplicationconteextutils.getwebapplicationcontext (Request.getServletContext);
Xxxservice interface = Wactx.getbean (Xxxservice interface. Class);
In addition to being able to obtain with webapplicationcontext, it is possible to obtain it with Classpathxmlapplicationcontext.
Classpathxmlapplicationcontext CTX = new Classpathxmlapplication ("Configuration file path string");
Xxxservice interface = Ctx.getbean ("String of ID", Xxxservice interface. Class);
These two methods can reduce the set method of the service interface.
The second solution is:
Use your own handwriting to reflect the package name and class name directly into a class, and then return to the object to solve, so you can not write the corresponding service set method, but such a
It is not necessary to build wheels.
The third solution is:
A new servlet is written, and can be implemented to give a full class name a reflection of an object, and then in each of the other servlets can be inherited in a way to create a variety of desired classes, but
This is still to write the various set methods.
The fourth solution is:
It's easy to use spring MVC at this time, whether it's configuration or annotations, and the way spring MVC is developed is a great advantage for your development efficiency.
Questions about the inability to inject service into the servlet in spring