java - 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
解决方案
它只是一个空指针的事实告诉您,Spring 甚至没有尝试在这里找到要注入的 bean。如果 Spring 尝试注入 @Autowired 但找不到匹配的 bean,它会告诉你。
这意味着AfiliadoActivoV
Springs Component-Scanning 不会拾取它,它收集所有 CDI-able 类。
@Component
用or注释你的类@Service
@Component public class AfiliadoActivoV {
确保在组件扫描期间可以找到该类。如果您依赖基于注释的配置,您将拥有一个使用
@SpringBootApplication
. 默认情况下,SpringBoot 只会扫描这个目录和所有子目录的 Bean 类。
我想您的@SpringBootApplication
-class 位于AfiliadoActivoV
.
在这种情况下,您可以修改您的类结构或使用@ComponentScan("...")
推荐阅读
- mysql - MySQL - 大表计算车辆平均速度
- translation - 日语、汉语和韩语的罗马化
- python - How can we do a Group By on Multiple fields and Select First or Max?
- javascript - 如何在 javascript 中访问 element.dataset.keyname
- javascript - ReactJs 从嵌套功能组件中的道具设置状态
- python - 用 MLE 和 Newton-Raphson 估计 Weibull
- scala - Scala - 将 1 个数据帧映射到另一个具有嵌套模式的数据帧
- ruby-on-rails - 重新格式化 mail.date 以与 db 中的 Date 字段(如果存在)进行比较。Ruby on Rails、ActionMailbox(邮件宝石)
- aws-lambda - 如何使用 aws-sdk 连接到基于 serverless-offline-ssm 构建的本地 SSM?
- django - Fargate 更新到 1.4 后 Django Collectstatic 的 AWS ECS PermissionError