在类中调用JPARepository实现返回NullPointerException错误

时间:2015-11-09 06:29:20

标签: java spring annotations

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

imports ...

public class TestClass {

   @Inject
   private JPARepositoryImpl jparepositoryimpl;

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

感谢。

1 个答案:

答案 0 :(得分:0)

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