【问题标题】:Spring boot with mongoDB returns NullPointerException使用 mongoDB 的 Spring Boot 返回 NullPointerException
【发布时间】:2020-01-08 17:36:07
【问题描述】:

最近,我正在尝试使用 MongoDB 和 Spring Boot。

我已经看过多个关于如何做到这一点的教程,但是当我尝试将对象插入数据库时​​遇到了问题。 问题是,SO 中提供的每个教程或答案都暗示我将调用通过 REST 函数扩展 MongoRepo 的存储库(结果,@Autowire 注释将实例化该类)。但是,我的程序并非如此,因为我需要通过位于不同包中的类调用 store 类,而该类不是通过 REST API 调用的。 第一个问题是扫描不同的包。我设法通过使用 baseScanPackages 和 @EnableMongoRepository 注释来解决它。我还创建了 MongoConfig 类,因为后者需要 MongoClient 实现。

但是,每次调用存储对象的类时,都会收到 NullPointerException。我知道问题在于,由于我通过新对象而不是 Autowire 调用该类,因此不会实例化接口。

我的问题是:有没有一种方法可以实例化扩展 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");
    }
}

调用保存方法的类的构造函数

StoreTemplates storeTemplates;
    /**
     * Constructor.
     * 
     * @param connection
     */
    public TemplateGeneral(Connection connection) {
        super(connection);
        storeTemplates = new StoreTemplates(); <- This will not trigger the @Autowired class
    }

谢谢!

【问题讨论】:

  • 如果直接放@Autowired private TemplateRepository templateRepository;呢?
  • @Oneguy 已经尝试过了,但我仍然遇到同样的问题。
  • 添加更多关于你的 Mongo DB 配置的代码,以及与之相关的数据。请
  • 如果自动装配 Repository 不起作用,您可能弄乱了目录结构并且 Spring 没有扫描 repo 类。检查存储库是否在 Spring 扫描的包中。
  • Spring 只会在由 spring 管理的类中自动装配。所以你实例化是行不通的。发布您的完整代码和完整的类实例化。并且还要说明你要解决什么,因为你现在做的事情很奇怪。

标签: java mongodb spring-boot


【解决方案1】:

最后一段代码不正确,实例化是通过 new 关键字完成的。直到或除非您不允许弹簧进行注射,这是使用弹簧的主要目的。我没有看到任何直接获取它的方法。

【讨论】:

    猜你喜欢
    • 2019-11-13
    • 2020-11-20
    • 2020-05-02
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 2017-09-17
    • 2020-05-24
    相关资源
    最近更新 更多