首页 > 解决方案 > java.lang.NullPointerException:当我调用存储库时为空

问题描述

下午好,我在这里尝试做的是通过 CUSPP 验证是否有一个对象会成为我的 ID,但是这个验证是在我的 @Controller 之外完成的,因此我想在我的 AffiliateActiveV 中进行,然后通过调用它AfiliadoActivoV obj = new AfiliadoActivoV()然后用数据填充它AfiliadoActivoV(cuspp)

我需要在 @Controller 类之外完成验证,因为 SonarLint 告诉我该类变得太大了。

AfiliadoActivoRepository

@Repository
public interface AfiliadoActivoRepository extends CrudRepository<AfiliadoActivoEntity, String> {
}

AfiliadoActivoController

@RestController
@CrossOrigin(origins = "*")
public class CargaArchivoController {
        @GetMapping(path = "/leertxt")
    public @ResponseBody String leerArchivo() {
        AfiliadoActivoV obj = new AfiliadoActivoV();
       return obj.validacionCampos(item.cuspp) //This value comes from a reading made to a csv file - I have validated with a System.out.Print and if it has data
    }
}

AfiliadoActivoV

public class AfiliadoActivoV {

    @Autowired
    AfiliadoActivoRepository crudAfiliadoActivo2;

public String validacionCampos(String cuspp) {
    String respuesta="";
    if(crudAfiliadoActivo2.existsById(cuspp)==true) {
         respuesta= respuesta + " Error: CUSPP Duplicado";
    }
}}

我附上了 STS 控制台中出现的错误 enter image description here

标签: javaspring-bootautowired

解决方案


它只是一个空指针的事实告诉您,Spring 甚至没有尝试在这里找到要注入的 bean。如果 Spring 尝试注入 @Autowired 但找不到匹配的 bean,它会告诉你。

这意味着AfiliadoActivoVSprings Component-Scanning 不会拾取它,它收集所有 CDI-able 类。

  1. @Component用or注释你的类@Service

    @Component
    public class AfiliadoActivoV {
    
  2. 确保在组件扫描期间可以找到该类。如果您依赖基于注释的配置,您将拥有一个使用@SpringBootApplication. 默认情况下,SpringBoot 只会扫描这个目录和所有子目录的 Bean 类。

我想您的@SpringBootApplication-class 位于AfiliadoActivoV.

在这种情况下,您可以修改您的类结构或使用@ComponentScan("...")


推荐阅读