在使用spring框架的过程中,受益于Spring框架中Bean的自动注入的方便,同时在JSP中需要使用到service层中的对象的时候,因为在service层都有dao层的自动注入,所以若是在JSP中直接使用如:
会出现空指针的情况,这种空指针是由于在ServiceUser中使用到了DaoUser的自动注入,也就是说,直接在JSP页面中实例化一个ServiceUser对象,其中的DaoUser是没有被注入的。为了解决这种状况,想到Spring这个容器在Web程序运行起来后,其中的所有对象都已经被装入到了ApplicationContext对象(即Spring容器)中,能不能直接从容器中把serviceUser这个Bean取出来呢?答案是肯定的,如下:
这样,在后面使用serviceuser这个对象再对数据库进行访问就不会再报空指针异常了。