SpringBoot @Autowired从服务类调用方法时出现 NullPointerException

SpringBoot @Autowired NullPointerException when calling method from service class

提问人:Veritas1832 提问时间:10/22/2021 最后编辑:Veritas1832 更新时间:10/27/2021 访问量:1036

问:

我正在学习Spring Boot。我正在尝试通过调用其方法从服务类的 ArrayList 中获取值。但是我得到了一个NullPointerException。我同时添加了@Autowired和@Service注释,它不起作用。我还查找了一些有关 Loc 容器的主题,但似乎没有帮助。

这是我的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";
    }
}

这是我的服务类:

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

下面是模型类 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 +
                '}';
    }
}

编辑:能够通过在MainController中添加构造函数来修复它

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

    @Autowired
    public MainController(ProductService productService) {
        this.productService = productService;
        this.products = productService.getAllProduct();
    }
spring-boot spring-mvc arraylist nullpointerexception 自动连线

评论


答:

2赞 Rahil Husain 10/22/2021 #1

在注入依赖项之前调用服务方法。这就是您获得 NPE 的原因。尝试使用构造函数依赖注入

@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";
}
}

或者调用控制器方法中的服务方法

@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";
}
}

评论

0赞 Veritas1832 10/23/2021
感谢您的回答,第二种方法效果很好。但是第一个仍然对我不起作用,它仍然提供 NPE。但是,如果我只使用 ''' private ProductService productService productService = new ProductService();''' 而不是使用 @Autowired
0赞 Veritas1832 10/23/2021
我可以通过在MainController构造函数中初始化产品来解决问题。所以它就像私有的 ProductService productService;private ArrayList<Product> 产品;public MainController(ProductService productService) { this.productService = productService; this.products = productService.getAllProducts();
0赞 noob 10/22/2021 #2

您的产品永远不会在产品服务类中初始化,我建议您在 ProductService 类中尝试此操作

    @Service
   public class ProductService {
   ArrayList<Product> products;
 ProductService()
{
        this.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;
                         } 
                    }
0赞 Aph1ka 10/26/2021 #3

很好,始终使用构造函数注入而不是字段注入。我只是转达 Spring 建议。这是最近采用最多的转换:)