我收到此错误
错误
org.springframework.web.util.NestedServletException:
Request processing failed; nested exception is java.lang.NullPointerException
...
root cause
java.lang.NullPointerException
com.javalabs.web.service.UserService.get(UserService.java:22)
我已经使用config和component-scan软件包配置了bean
UserService.java
@Service("userService")
public class UserService {
private UserDao userDao;
@Autowired
private void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public User get(String username){
return userDao.get(username); //Error in this line userDao = null
}
...
TaskController.java
@Controller
public class TaskController {
...
private UserService userService;
...
@Autowired
public void setCategoryService(CategoryService categoryService) {
this.categoryService = categoryService;
}
...
@RequestMapping(value = "/docreatetask", method = RequestMethod.POST)
public String doCreateTask(Model model, @Valid Task task,
BindingResult result, Principal principal,
@RequestParam(value = "delete", required = false) String delete) {
System.out.println(">TaskController doCreateTask " + task + " | delete: "+ delete);
if (result.hasErrors()) {
System.out.println("/docreatetask in here");
model.addAttribute("task", task);
return "createtask";
}
if(delete == null){
String username = principal.getName();
task.setIdUser(new UserService().get(username).getIdUser());
task.setDate(new Date());
taskService.create(task);
System.out.println(">TaskController: Form does validate");
return "taskcreated";
}
else {
return "taskdeleted";
}
}
...
有什么想法吗?
答案 0 :(得分:1)
问题在于:
task.setIdUser(new UserService().get(username).getIdUser());
您手动创建bean。你应该让Spring创建bean并使用它。
只需自动连接UserService
课程中的TaskController
:
@Controller
public class TaskController {
@Autowired
UserService userService;
//...
@RequestMapping(value = "/docreatetask", method = RequestMethod.POST)
public String doCreateTask(Model model, @Valid Task task,
BindingResult result, Principal principal,
@RequestParam(value = "delete", required = false) String delete) {
//current code...
task.setIdUser(userService.get(username).getIdUser());
//rest of your code...
}
}