zoukankan      html  css  js  c++  java
  • 关于 spring 使用 mongodb 的 mongotemplate 对象操作数据库,对象注入问题(即该对象能否正常的调用相应的CRUD方法来处理数据)

    通过 spring 框架,直接调用一些处理对象的方法和数据库交互, http 接口从 controller 层调用开始, 如果是:controller --> service --> dao --> entity 这个流程正常调用,则:

    (1)controller1 --> service1 --> dao1 -->entity1 

    (2)controller1 --> service2 --> dao2 -->entity2 (类推 3、4、5……都可以正常执行)

    但是如果:

    (3)controller1 --> controller2 --> service1 --> dao1 -->entity1 

    (4)controller1 --> controller2 --> service2 --> dao2 -->entity2

    会产生:这种由于逻辑需要,需要先在同一 controller 层,先调用其它 controller 类(直接 new 该类处理一下数据),再回来执行自己实体类操作(或者其他实体类操作)的时候,这种情况下,controller2 里面的 mongotemplate 对象,这个时候是一个 null 对象,是不能正常调用该对象对应的操作数据库的方法,来执行自己本身的逻辑的,也就是说,这个时候调用 controller2 类里面的方法,都是不能正常执行的!

    解决方法:想要 controller2 在 controller1 里面调用能都正常执行,由于这时候,mongotemplate 在 controller2 中是 null 值,只要在 controller1 中把 mongotemplate 对象传入给 controller2 中即可!(可以通过在 controller2 中添加构造方法,在 controller1 中 new controller2(MongoTemplate mongotemplate) 时候把 mongotemplate 对象传入 controller2 ,即可解决该问题!)

    【http 通过 controller 进来的 mongotemplate 对象才会注入 spring ,才能正常使用,如果是通过其他 controller 类来调用同层的 controller 里面的 mongotemplate ,则该对象是 null 值,不可使用 !而从 controller 调用 service 这种不同层的,则可以正常使用!】

  • 相关阅读:
    vue苦逼自学之路
    第一次博客作业
    u3d学习资料
    leetcode——Divide Two Integers
    leetcode——Swap Nodes in Pairs
    leetcode——Merge k Sorted Lists
    leetcode——Container With Most Water
    leetcode——Regular Expression Matching
    leetcode——Longest Palindromic Substring
    CC_CALLBACK之间的区别
  • 原文地址:https://www.cnblogs.com/xuehuashanghe/p/10394029.html
Copyright © 2011-2022 走看看