背景:spring+springmvc+mybatis
问题:service包已经设置了自动扫描,然后自己在写control时,居然自己new了一个,如下
ProductsTypeServiceImpl ptl=new ProductsTypeServiceImpl();
报错如下:
严重: Servlet.service() for servlet [dispatcher] in context with path [/shop] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at shop.service.impl.ProductsTypeServiceImpl.queryAllType(ProductsTypeServiceImpl.java:25)
刚开始以为是包自动扫描出了问题,后来才反应过来,改成如下即可
@Autowired
private ProductsTypeServiceImpl ptl;
进一步思考:为什么不让自己new呢?
我往前翻,service类用了注解@service,如果不用自动扫描service包,自己来new呢?试了下,结果还是不行。再往前翻,service用了dao,dao是@Autowired注解注册的,所有上一步才不行,然后我想自己来new一个dao,结果new不出来,呃呃,dao是mybatis注册到spring里的,直接写的接口,没写实体类,new不出来了,就到这里吧!