![](/img/trans.png)
[英]Spring Boot URL Request Mapping Returns NullPointerException
[英]Spring boot with mongoDB returns NullPointerException
最近,我正在嘗試使用 MongoDB 和 Spring Boot。
我看過多個關於如何執行此操作的教程,但是當我嘗試將對象插入數據庫時遇到了問題。 問題是,SO 中提供的每個教程或答案都暗示我將調用通過 REST 函數擴展 MongoRepo 的存儲庫(結果,@Autowire 注釋將實例化該類)。 但是,這不是我的程序的情況,因為我需要通過位於不同包中的類調用存儲類,該類不是通過 REST API 調用的。 第一個問題是掃描不同的包。我設法通過使用 baseScanPackages 和 @EnableMongoRepository 注釋來解決它。 我還創建了 MongoConfig 類,因為后者需要 MongoClient 實現。
但是,每次調用存儲對象的類時,都會得到NullPointerException 。 我知道問題在於,由於我通過新對象調用該類而不是自動裝配它,因此不會實例化該接口。
我的問題是:有沒有一種方法可以實例化擴展 MongoRepository 的接口而不必自動裝配它?
下面是代碼:
界面
@Repository
public interface TemplateRepository extends MongoRepository<Template,String> {
}
店鋪類
@Component
public class StoreTemplates {
\\The issue is here. This class is never instantiated.
private TemplateRepository templateRepository;
@Autowired
public StoreTemplates(TemplateRepository templateRepository) {
this.templateRepository=templateRepository;
}
public void store(Template template){
if(templateRepository!=null)
templateRepository.save(template);
else
System.out.println("not initialised");
}
}
調用 save 方法的類的構造函數
StoreTemplates storeTemplates;
/**
* Constructor.
*
* @param connection
*/
public TemplateGeneral(Connection connection) {
super(connection);
storeTemplates = new StoreTemplates(); <- This will not trigger the @Autowired class
}
謝謝!
最后一段代碼不正確,其中實例化是通過 new 關鍵字完成的。 直到或除非您不允許彈簧進行注射,這是使用彈簧的主要目的。 我沒有看到任何直接獲得它的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.