繁体   English   中英

每当我尝试在mysql数据库中插入数据时(在springboot java上),自动装配的存储库都会收到nullPointerException错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM