![](/img/trans.png)
[英]Why do I get NullPointerException with @Autowired Repository in Vaadin / SpringBoot application?
[英]Autowired repository gets a nullPointerException error everytime i try to insert data in mysql database (on springboot java)
所以我一直在尝试在我自己创建的另一个类中添加一些新数据(而不是在Controller下方的默认类中)
所以这是解释它的代码:
MainController.java
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import hello.User;
import hello.UserRepository;
@Controller
@RequestMapping(path="/demo")
public class MainController {
@Autowired
private UserRepository userRepository;
@GetMapping(path="/add")
public @ResponseBody String addNewUser () {
pge j = new pge();
j.pgl(); //here's the code to add data in mysql
return "Saved";
}
}
这是我的pge.java中的代码
package hello;
import org.springframework.beans.factory.annotation.Autowired;
public class pge {
@Autowired
private UserRepository userRepository;
public void pgl() {
User n = new User();
n.setName("sarah");
n.setEmail("sarah@gmail.com");
userRepository.save(n);
}
}
每次我打开localhost:8080 / demo / add时,在Web中它只会给出whitelabel错误页面,而在Java中它会给出null错误。 我要做的就是在自己的类中的数据库(MySQL)中添加新数据。
由于pge
对象不受Spring的管理,因此autowired
注释将不会注入UserRepository
bean。 我建议将pge
更改为Spring托管bean。
@Service
public class pge {
@Autowired
private UserRepository userRepository;
...
}
并在主控制器中
@Controller
@RequestMapping(path="/demo")
public class MainController {
@Autowired
private UserRepository userRepository;
@Autowired
private pge pge;
@GetMapping(path="/add")
public @ResponseBody String addNewUser () {
pge.pgl(); //here's the code to add data in mysql
return "Saved";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.