SpringBoot @Autowired NullPointerException when calling method from service class

Veritas1832

I'm learning Spring Boot. I'm trying to fetch a value from an ArrayList from the service class by calling its method. But I got a NullPointerException. I add both @Autowired and @Service annotations, it doesn't work. I also looked up some topics about Loc container but it doesn't seem to help.

Here is my MainController:

package com.example.ecommerce;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;

@Controller
public class MainController {



    @Autowired
    private ProductService productService;
    //I'm getting a NullPointerException here when I call the method "getAllProduct"
    ArrayList<Product> products = productService.getAllProduct();

    @GetMapping("/")
    public String home(){
        return "home";
    }

    @GetMapping("/products")
    public String product(Model model){
        model.addAttribute("products",products);
        return "product";
    }
}

Here is my service class:

package com.example.ecommerce;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class ProductService {

    ArrayList<Product> products = new ArrayList<>(Arrays.asList(
            new Product("iPhone 4","Apple",1000),
            new Product("iPhone 5","Banana",2000),
            new Product("iPhone 6","Orange",3000)
    ));


    public ArrayList<Product> getAllProduct(){
        return products;
    }
}

Here is the model class Product:

package com.example.ecommerce;


import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;
    private String brand;
    private double price;

    public Product() {
    }

    public Product(String name, String brand, double price) {
        this.name = name;
        this.brand = brand;
        this.price = price;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

Edit: was able to fix it by adding a constructor in the MainController

    private final ProductService productService;
    private final ArrayList<Product> products;

    @Autowired
    public MainController(ProductService productService) {
        this.productService = productService;
        this.products = productService.getAllProduct();
    }
Rahil Husain

The service method is called before the dependency is injected. That's why you are getting NPE. Try using constructor dependency injection

@Controller
public class MainController {

public MainController(ProductService productService) {
    this.productService = productService;
}

private ProductService productService;
//I'm getting a NullPointerException here when I call the method "getAllProduct"
ArrayList<Product> products = productService.getAllProduct();

@GetMapping("/")
public String home() {
    return "home";
}

@GetMapping("/products")
public String product(Model model) {
    model.addAttribute("products", products);
    return "product";
}
}

Or call the service method inside the controller method

@Controller
public class MainController {

@Autowired
private ProductService productService;

@GetMapping("/")
public String home() {
    return "home";
}

@GetMapping("/products")
public String product(Model model) {
    model.addAttribute("products", productService.getAllProduct());
    return "product";
}
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

NullPointerException when calling a method from a different class

From Java

NullPointerException when calling method from another class

From Dev

NullPointerException while calling a method from service

From Java

Calling service method from another service class

From Dev

NullPointerException when calling a Fragment method from Activity?

From

Calling activity class method from Service class

From Dev

Mockito - NullpointerException when invoking method from Service

From Dev

Mockito : java.lang.NullPointerException when calling method from mocked Class

From Dev

Calling method from another class in onPostExecute causing nullPointerException

From Dev

NullPointerException when calling a mocked method

From Dev

NullPointerException when calling mocked method

From Dev

NullPointerException when calling EJB method

From Dev

NullPointerException when calling Redis method

From Dev

NullPointerExceptionError when calling method from class

From Dev

NullPointerException when calling a method from a dynamic object array

From Java

Autowired a method from the @Config class

From Java

SpringBoot Component autowired from Test class null

From Dev

Dependency Injection in Angular/ Calling a method that belongs to a service from a class

From Dev

Calling a method from a class

From Dev

JButton listener calling method in class gives NullPointerException

From Dev

calling a method by class level annotated with @RequestMapping that includes an autowired class

From Dev

NullPointerException for Springboot @Autowired component in interceptor

From Dev

Calling a web service from android - NullPointerException

From Dev

When Calling Other Activity Method Showing NullPointerException

From Java

Python error when calling NumPy from class method with map

From Dev

Calling method from inheriting class when async logic completes in BaseClass

From Java

Java cannot find symbol when calling a method from another class

From Dev

python - remain in base class when calling parent method from child

From Dev

How to obtain the derived class type from base when calling a method

Related Related

  1. 1

    NullPointerException when calling a method from a different class

  2. 2

    NullPointerException when calling method from another class

  3. 3

    NullPointerException while calling a method from service

  4. 4

    Calling service method from another service class

  5. 5

    NullPointerException when calling a Fragment method from Activity?

  6. 6

    Calling activity class method from Service class

  7. 7

    Mockito - NullpointerException when invoking method from Service

  8. 8

    Mockito : java.lang.NullPointerException when calling method from mocked Class

  9. 9

    Calling method from another class in onPostExecute causing nullPointerException

  10. 10

    NullPointerException when calling a mocked method

  11. 11

    NullPointerException when calling mocked method

  12. 12

    NullPointerException when calling EJB method

  13. 13

    NullPointerException when calling Redis method

  14. 14

    NullPointerExceptionError when calling method from class

  15. 15

    NullPointerException when calling a method from a dynamic object array

  16. 16

    Autowired a method from the @Config class

  17. 17

    SpringBoot Component autowired from Test class null

  18. 18

    Dependency Injection in Angular/ Calling a method that belongs to a service from a class

  19. 19

    Calling a method from a class

  20. 20

    JButton listener calling method in class gives NullPointerException

  21. 21

    calling a method by class level annotated with @RequestMapping that includes an autowired class

  22. 22

    NullPointerException for Springboot @Autowired component in interceptor

  23. 23

    Calling a web service from android - NullPointerException

  24. 24

    When Calling Other Activity Method Showing NullPointerException

  25. 25

    Python error when calling NumPy from class method with map

  26. 26

    Calling method from inheriting class when async logic completes in BaseClass

  27. 27

    Java cannot find symbol when calling a method from another class

  28. 28

    python - remain in base class when calling parent method from child

  29. 29

    How to obtain the derived class type from base when calling a method

HotTag

Archive