簡體   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