0

I'm new to Java and Spring. My problem is that using the autowired field in some of my controller functions throws NullPointerException.

@Controller
@RequestMapping("/customer")
public class CustomerController {
     
    @Autowired
    private CustomerService customerService;
    
    @GetMapping("/list")
    public String listCustomers(Model model) {
        List<Customer> customers = customerService.getCustomers();
        model.addAttribute("customers", customers);
        return "list-customer";
    }

    @PostMapping("/save")
    private String save(@ModelAttribute("customer") Customer customer) {
        customerService.saveCustomer(customer);
        return "redirect:/customer/list";
    }

    @GetMapping("/delete")
    private String delete(@RequestParam("customerId") int id, Model model) {
        customerService.removeCustomer(customerService.getCustomer(id));
        return "redirect:/customer/list";
    }
}

This happens in the save or delete function but not in the list.

java.lang.NullPointerException: Cannot invoke "com.hamid.springdemo.service.CustomerService.getCustomer(int)" because "this.customerService" is null

I should mention that I recently added AOP support to my project, but I have no idea whether it is related or not.

HamidYari
  • 21
  • 1
  • 7
  • 1
    Does class `CustomerService` have a bean-defining annotation (`@Service`, `@Component`, ...)? --- I recommend reading: [What exactly is Field Injection and how to avoid it?](https://stackoverflow.com/questions/39890849/what-exactly-is-field-injection-and-how-to-avoid-it) – Turing85 Nov 26 '22 at 20:21
  • Yes, it does. I wonder how is it working in list function :( `@Service public class CustomerServiceImpl implements CustomerService { //services }` @Turing85 – HamidYari Nov 26 '22 at 20:36
  • 1
    Can you provide a [MRE], e.g. in form of a github project? – Turing85 Nov 26 '22 at 20:41
  • I'm just learning and I'm watching the Udemy course and writing the code simultaneously. I can share zip of my project, is it good? – HamidYari Nov 26 '22 at 20:44
  • 1
    I am not willing to download some zip from somewhere. Creating a github account is free and not time-consuming. Learning git should be on your to-dos anyway, and you should be up and running within minutes. – Turing85 Nov 26 '22 at 20:46

0 Answers0