[英]Spring Boot MongoRepository Null Pointer Exception
我對春天來說有點新鮮,而且我遇到了一個空指針異常。 我相信@Autowired
不能用於我的MongoRepository。 出於某種原因,當我嘗試一些例子時,它正在運作。 (運行函數中注釋掉的代碼有效)
這是我得到的錯誤:
2016-05-20 02:31:20.877 ERROR 6272 --- [nio-8080-exec-2] oaccC [。[。[/]。[dispatcherServlet]:servlet [dispatcherServlet]的Servlet.service()與上下文path []引發異常[請求處理失敗; 具有根本原因的嵌套異常是java.lang.NullPointerException]
java.lang.NullPointerException:在com.applesauce.service.CustomerService.addCustomer(CustomerService.java:24)〜[classes /:na]中為null
你們可以看看並指導我嗎? 另外,如果我為最佳做法做錯了,請告訴我。 如果您需要更多信息,請詢問!
com.applesauce.controller
@RestController
@RequestMapping("/customer")
public class CustomerController {
private CustomerService customerService = new CustomerService();
@RequestMapping(value = "/addcustomer", method = RequestMethod.GET)
public Customer addCustomer(@RequestParam("firstName") String fName,
@RequestParam("lastName") String lName,
@RequestParam("email") String email,
@RequestParam("phoneNumber") String phoneNumber,
@RequestParam("source") String source){
return customerService.addCustomer(new Customer(fName,lName,email,phoneNumber,source));
}
}
com.applesauce.repository
@Repository
public interface CustomerRepository extends MongoRepository<Customer, String> {
public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
}
com.applesauce.service
@EnableMongoRepositories(basePackages = "com.applesauce.repository")
public class CustomerService {
@Autowired
private CustomerRepository repository;
public Customer addCustomer(Customer customer){
repository.save(customer);
return customer;
}
}
Xtreme Biker意味着你應該為你的CustomerService添加@Service注釋,如下所示:
@EnableMongoRepositories(basePackages = "com.applesauce.repository")
@Service
public class CustomerService {
...
}
此外,如果您希望Spring關注它,您永遠不想使用new運算符創建服務。 在CustomerController中,更改初始化行:
private CustomerService customerService = new CustomerService();
至:
@Autowired
private CustomerService customerService;
它必須解決NullPointerException。
我有同樣的問題,我解決了這個問題(解釋是通用的)
Repository.class
@Repository
public interface {...}
Service.class
public class {...}
@Autowired
private Repository repo;
Application.class
@Autowired Service service;
service.method() //does not throws NullPointerException
檢查您是否已創建具有@Service注釋(使用new)的類的對象。 此類也應該是自動裝配的,您已經自動裝配了存儲庫bean。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.