项目里面想在servlet用spring注入的service等bean的时候,报空指针异常,网上的解释:
其实我们使用spring的目的就是为了让spring为我们来提供一个已经被注入好的一个实例。而servlet是不同的,servlet是有生命周期的,而这个并不归属spring管理,而是由web容器管理的。那么当servlet刚刚创建的时候,spring可以为servlet注入,当你访问的时候,由于servlet是单实例多线程的,所以,servlet信息被重置,刚刚被注入的对象又为null了。
我有一些问题,
servlet是单实例的,但是如果我注入的bean是成员变量,那么即使是多次请求,这个bean 也是在堆内存里面,为什么servlet信息会被重置呢?
如果是spring mvc,为什么在controller里面可以直接调用其他spring 容器管理的bean。
如果我在servlet里面调用service , service里面再调用spring注入的bean还会有空指针的问题吗?
谢谢.
As you said: Servlet is a single instance, there is only one Servlet object in the container to handle all client requests, therefore:
1. Servlet can store some global or unchanged data, but user-related data should not be stored. Otherwise, multiple users will operate these data in different threads at the same time, which will lead to confusion.
2. There is also a Servlet in mvc, but this servlet will create a new Controller every time it makes a request, so that the data does not interfere with each other during a request processing by the Servlet. In addition, generally the beans managed by spring will be stored in objects such as ThreadLocal. After the controller is processed, the ThreadLocal will be cleaned up.
3. The principle is the same as above. If you write it separately, you should create a new service, and finally clean up the ThreadLocal after the processing is completed. Otherwise, the residual data will be left for the next data processing, resulting in unpredictable data.