eclipse环境下的springboot框架+mybatis访问MySQL报错空指针
最近在写springboot项目时,在开始阶段遇到了一个问题,我按照教程搭建好框架之后,利用mybatis访问MySQL数据库,但是不管执行增加还是查询数据库方法都报空指针异常,
错误截图如下:
2020-01-07 22:22:53.793 ERROR 2304 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
在进行很多种解决方法后还是不行,一直报空指针,后来看了看controller类中的代码,我最开始是这么写的
@Controller @RequestMapping("/") public class TestController { @RequestMapping("/login") public String login() { List<Duorou_goods> users = new ArrayList<Duorou_goods>(); UserService userService = new UserService(); users = userService.selectUser(); return "html/login"; } }
我把UserService的声明放在了方法里,原因就出在这里,UserService对象的声明应该在controller类最外层,以属性的方式声明,例如:
@Controller @RequestMapping("/") public class TestController { @Autowired UserService userService; @RequestMapping("/login") public String login() { System.out.println("ok1"); List<Duorou_goods> users = new ArrayList<Duorou_goods>(); users = userService.selectUser(); return "html/login"; } }
而且要在UserService对象前加@Autowried注解才行。
这个问题困扰了我很久,解决之后也不太清楚原理是什么,还需要继续学习。
相关推荐
Dullonjiang 2020-08-09
牧场SZShepherd 2020-07-20
xiuyangsong 2020-11-16
Nishinoshou 2020-11-09
jimgreatly 2020-09-01
dongxurr 2020-08-18
Dullonjiang 2020-08-15
Dullonjiang 2020-08-11
dongxurr 2020-08-08
yunzhonmghe 2020-08-07
jimgreatly 2020-08-03
Dullonjiang 2020-07-30
jimgreatly 2020-07-27
liqiancao 2020-07-26
xiuyangsong 2020-07-26
dongxurr 2020-07-26
mcvsyy 2020-07-26
helloxusir 2020-07-25