【问题标题】:Called JPARepository Implementation inside a Class returns NullPointerException Error在类中调用 JPARepository 实现返回 NullPointerException 错误
【发布时间】:2015-11-09 06:29:20
【问题描述】:

我正在开发一个 Spring java 项目。我有这个类需要更新一个数据库行。我正在使用 JPARepository 进行数据库操作。但是当我从一个类中调用这个实现时,这会返回一个 NullPointerException。

imports ...

public class TestClass {

   @Inject
   private JPARepositoryImpl jparepositoryimpl;

   public void split () {
      jparepositoryimpl.findByFilename(filename);
   }
}

谢谢。

【问题讨论】:

  • 如何创建TestClass的实例?你调用 new TestClass() 吗?
  • 此 TestClass 用于拆分文件。拆分完成后,我需要调用 jparepository 函数以按文件名列查找行。
  • 是的,很好的评论,但这并不能回答我的问题。请显示代码,在其中实例化 TestClass。
  • 对不起,我把你的问题弄错了。是的,我将 TestClass 实例化为 new TestClass()。
  • @WebServlet("/ServletA") public class ServletA extendes HttpServlet { TestClass testclass = new TestClass(); protected doGet(...) { testclass.split(); } }

标签: java spring annotations


【解决方案1】:

如果您使用new TestClass() 实例化一个类,Spring 对该实例一无所知,并且自动装配将不起作用。您必须使 TestClass 成为 Spring Bean(通过使用 @Component 注释它或通过 @Bean 注释方法创建对象实例)并将其注入您需要的地方。

【讨论】:

  • 返回错误的行是 jparepositoryimpl.findByFilename(filename);
  • 似乎 TestClass 无法识别我的 jparepositoryimpl? :(
  • 当然,因为TestClass不是由Spring管理的,所以JPARepositoryImpl不会被Spring注入。我建议你从一些关于 Spring 中的注入如何工作的基本教程开始。
猜你喜欢
  • 1970-01-01
  • 2020-10-11
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 2015-05-09
相关资源
最近更新 更多