Birger Huysmans
Birger Huysmans

Reputation: 13

Spring Repository nullpointerexception

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();
    }

}

Going to http://localhost:8080/customer returns every customer in my database just fine.

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?

Upvotes: 1

Views: 6354

Answers (1)

watchme
watchme

Reputation: 740

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();
}

}

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.

Upvotes: 3

Related Questions