Spring Repository 空指针异常 [英] Spring Repository nullpointerexception
问题描述
我正在尝试使用 Spring-Boot 编写一个非常基本的应用程序.我目前唯一尝试的是从 SQL Server 数据库中获取一些信息.
I'm trying to write a really basic application using Spring-Boot. The only thing I'm currently trying is to get some information out of a SQL Server database.
Application.java
@SpringBootApplication(scanBasePackageClasses = { MainView.class, Application.class })
@EnableJpaRepositories(basePackageClasses = CustomerRepository.class)
@EntityScan(basePackageClasses = Customer.class)
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
Customerrepository.java
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer>
{
}
CustomerController.java
@Controller
@RequestMapping(path = "/customer")
public class CustomerController {
@Autowired
private CustomerRepository customerRepository;
@GetMapping(path = "/all")
public @ResponseBody Iterable<Customer> getAllCustomers() {
return customerRepository.findAll();
}
}
CustomersView.java
@Tag("customers-view")
@HtmlImport("src/views/customers/customers-view.html")
@Route(value = ApplicationConst.PAGE_CUSTOMERS, layout = MainView.class)
@PageTitle(ApplicationConst.TITLE_CUSTOMERS)
public class CustomersView extends PolymerTemplate<TemplateModel> {
@Autowired
CustomerRepository customerRepository;
public CustomersView() {
customerRepository.findAll();
}
}
转到 http://localhost:8080/customer 会很好地返回我数据库中的每个客户.
Going to http://localhost:8080/customer returns every customer in my database just fine.
但是当我尝试在我的 CustomersView.java 中查找所有客户时,自动装配的 CustomerRepository 返回空指针异常.
But when I try to find all the customers in my CustomersView.java, the autowired CustomerRepository returns a nullpointerexception.
有人能指出我正确的方向吗?
Is somebody able to point me in the right direction?
推荐答案
尝试在构造函数中@Autowire Repository 像这样:
Try to @Autowire the Repository in the constructor like this:
@Tag("customers-view")
@HtmlImport("src/views/customers/customers-view.html")
@Route(value = ApplicationConst.PAGE_CUSTOMERS, layout = MainView.class)
@PageTitle(ApplicationConst.TITLE_CUSTOMERS)
public class CustomersView extends PolymerTemplate<TemplateModel> {
CustomerRepository customerRepository;
@Autowired
public CustomersView(CustomerRepository customerRepository) {
this.costumerRepository = customerRepository;
this.customerRepository.findAll();
}
}
发生这种情况是因为所有@autowired-attributes 都是在构造函数完成后插入的.如果你想在构造函数时注入@autowired-attributes,你必须使用上面的方法.
This happens because all @autowired-attributes are inserted after the constructor gets completed. If you want to inject the @autowired-attributes at constructor-time, you have to use the method above.
这篇关于Spring Repository 空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!