【问题标题】:Exception in thread "main" java.lang.NullPointerException: "this.playerRepository" is null [duplicate]线程“main”java.lang.NullPointerException中的异常:“this.playerRepository”为空[重复]
【发布时间】:2021-04-15 10:21:40
【问题描述】:

每个人。我正在尝试构建一个游戏应用程序,但遇到了问题。我创建了一个 Spring 存储库、实体和服务,但每当我调用后者时,我都会遇到异常说明:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.example.demo.repo.PlayerRepository.findById(Object)" because "this.playerRepository" is null
    at com.example.demo.service.PlayerService.findPlayerById(PlayerService.java:16)
    at com.example.demo.DemoApplication.main(DemoApplication.java:16)

以下是我提供的课程,以展示我在程序中包含的内容:

玩家实体:

package com.example.demo.model;

import javax.persistence.*;
import java.util.Objects;

@Entity
@Table(name = "player", schema = "public", catalog = "gamestats")
public class PlayerEntity {
    private long id;
    private int health;
    private int damage;
    private int absorb;
    private int regen;
    private int fire;

    @Id
    @Column(name = "id")
    public long getId() {
        return id;
    }

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

    @Basic
    @Column(name = "health")
    public int getHealth() {
        return health;
    }

    public void setHealth(int health) {
        this.health = health;
    }

    @Basic
    @Column(name = "damage")
    public int getDamage() {return this.damage; }

    public void setDamage(int damage) {
        this.damage = damage;
    }

    @Basic
    @Column(name = "absorb")
    public int getAbsorb() {
        return absorb;
    }

    public void setAbsorb(int absorb) {
        this.absorb = absorb;
    }

    @Basic
    @Column(name = "regen")
    public int getRegen() {
        return regen;
    }

    public void setRegen(int regen) {
        this.regen = regen;
    }

    @Basic
    @Column(name = "fire")
    public int getFire() {
        return fire;
    }

    public void setFire(int fire) {
        this.fire = fire;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PlayerEntity that = (PlayerEntity) o;
        return id == that.id && health == that.health && damage == that.damage && absorb == that.absorb && regen == that.regen && fire == that.fire;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, health, damage, absorb, regen, fire);
    }
}

播放器存储库:

package com.example.demo.repo;

import com.example.demo.model.PlayerEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface  PlayerRepository extends JpaRepository<PlayerEntity, Long> {
}

播放器服务:

package com.example.demo.service;

import com.example.demo.model.PlayerEntity;
import com.example.demo.repo.PlayerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PlayerService{
    @Autowired
    PlayerRepository playerRepository;

    private PlayerEntity playerEntity;

    public PlayerEntity findPlayerById(long id) {
        return playerRepository.findById(id).get();
    }

    public void safePlayer(PlayerEntity test){ playerRepository.save(test); }


    public int getPlayerStrength(long id) {
        return playerRepository.findById(id).get().getHealth();
    }
}

DemoApplication:

package com.example.demo;

import com.example.demo.service.PlayerService;
import org.json.JSONException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) throws IOException, InterruptedException, JSONException {
        SpringApplication.run(DemoApplication.class, args);
        PlayerService playerService = new PlayerService();
        playerService.findPlayerById(1);
    }

非常感谢您的帮助,因为老实说我被困住了。

【问题讨论】:

    标签: java spring spring-boot rest


    【解决方案1】:

    服务需要自动装配存储库;只有当它是由 Spring 上下文创建时才会发生。通过 new 在 main 中创建它,Spring 没有机会向其中注入任何东西,因此它的字段仍然是 null

    如果您想使用该服务,您需要通过确保已正确创建上下文的方法来访问它。例如,您可以使用@PostConstruct 方法来做到这一点。

    @SpringBootApplication
    public class DemoApplication {
        // usually not held in an application class, but will work
        @Autowired
        private PlayerService service;
    
        public static void main(String[] args) throws IOException, InterruptedException, JSONException {
            SpringApplication.run(DemoApplication.class, args);
        }
       
      @PostConstruct
      public void doStuff() {
        // the service will have been initialized and wired into the field by now
        service.findPlayerById(1);
      }
    

    【讨论】:

      【解决方案2】:

      您必须使用 Optional 来确定是否存在与任何玩家 id 对应的空值。您可以遵循以下语法。

          public PlayerEntity findPlayerById(long id) {
              Optional<PlayerEntity> result=playerRepository.findById(id);
      
              PlayerEntity  player=null;
              if(result.isPresent()){
                  player=result.get();
              }else{
                  throw new RuntimeException("Did not find player id"+id);
              }
              return player;
      
          }
      

      【讨论】:

      • 这不会帮助存储库为空,但作为注释,您可以更简洁地将其写为return repo.findById(id).orElseThrow(new RuntimeException("no such id "+ id))
      猜你喜欢
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      相关资源
      最近更新 更多