Spring 启动 MongoRepository 空指针异常

Spring Boot MongoRepository Null Pointer Exception

我对 spring 有点陌生,我 运行 遇到了空指针异常。 我相信 @Autowired 在我的 MongoRepository 上不起作用。 出于某种原因,当我尝试一些示例时它正在工作。 (运行 函数中注释掉的代码有效)

这是我得到的错误:

2016-05-20 02:31:20.877 ERROR 6272 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null at com.applesauce.service.CustomerService.addCustomer(CustomerService.java:24) ~[classes/:na]

你们可以看看并指导我吗? 另外,如果我在最佳实践方面做错了什么,请告诉我。 如果您需要更多信息,请询问!

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

检查您是否创建了 class 的对象,该对象具有 @Service 注释(使用 new)。这个 class 也应该是自动装配的,你已经自动装配了你的存储库 bean。