我可以在不是RestController之类的类中访问我的存储库吗?
我有一个WatchService,他可以监听文件夹,读取文件并保存到数据库中。我的watchservice就像读取文件一样工作,但是我想使用我的JPARepository持久保存,我可以这样做吗?
Springboot应用程序v2.1.6.RELEASE
@Repository
public interface MyRepository extends JpaRepository<MyClass, Long> { }
public class MyWatchService implements Runnable{
@Autowired
private MyRepository myRepository;
// SOME CODES COMES HERE
@Override
public void run() {
// SOME CODES COMES HERE
myRepository.save(MyClass); // In this point give a nullPointerException
}
}
我收到该异常:
java.lang.NullPointerException
at com.WatchService.run(WatchService.java:515)
at java.base/java.lang.Thread.run(Thread.java:835)
答案 0 :(得分:0)
您得到NullPointerException
,因为没有注入依赖项。您正确使用了注释,但是由于某种魔力,没有注入依赖项。
为了使其正常工作(即注入豆),您需要让DI-或IoC容器实例化您的豆(在JEE中为CDI,在Spring中为Spring IoC Container)。可以通过注入(d'uh!注入起始)或以编程方式完成。
在this question中探索了以弹簧为中心的解决方案。