【问题标题】:MongoTemplate null pointer exception in class类中的 MongoTemplate 空指针异常
【发布时间】:2018-06-01 20:34:47
【问题描述】:

我一直在寻找其他答案,但似乎没有一个对我有用,我有一个使用 mongo 和 kafka 的 spring boot 应用程序。在我的 run() 方法所在的主类中,我能够 @Autowired mongoTemplate 并且它可以工作,但是在另一个类中我做了同样的事情,我在 mongoTemplate 上得到了一个空指针异常。

这是两个类:

工作

@SpringBootApplication
public class ProducerConsumerApplication implements CommandLineRunner {

public static Logger logger = LoggerFactory.getLogger(ProducerConsumerApplication.class);

public static void main(String[] args) {
    SpringApplication.run(ProducerConsumerApplication.class, args).close();
}

@Autowired
private Sender sender;

@Autowired
MongoTemplate mongoTemplate;


@Override
public void run(String... strings) throws Exception {
    Message msg = new Message();
    msg.setCurrentNode("my_node");
    msg.setStartTime(System.currentTimeMillis());
    String json = "{ \"color\" : \"Orange\", \"type\" : \"BMW\" }";
    ObjectMapper objectMapper = new ObjectMapper();
    msg.setTest(objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){}));
    sender.send(msg);

    mongoTemplate.createCollection("test123");
    mongoTemplate.dropCollection("test123");



}

不工作

@Component
public class ParentNode extends Node{
@Autowired
public MongoTemplate mongoTemplate;

public void execute(Message message) {

    try{

        // GET WORKFLOWS COLLECTION
        MongoCollection<Document> collection = mongoTemplate.getCollection("workflows"); 


    } catch(Exception e){
        e.printStackTrace();
    }
}

}

感谢您的帮助。非常感谢。

【问题讨论】:

    标签: spring mongodb spring-boot mongotemplate


    【解决方案1】:

    你能尝试用setter或constructor注入依赖吗:

    方法一:

    @Component
    public class ParentNode extends Node{
    
      @Autowired
      public ParentNode(MongoTemplate mongoTemplate){
        this.mongoTemplate = mongoTemplate;
      }
    
      private final MongoTemplate mongoTemplate;
    
      public void execute(Message message) {
    
      try{
    
          // GET WORKFLOWS COLLECTION
          MongoCollection<Document> collection = mongoTemplate.getCollection("workflows"); 
    
    
      } catch(Exception e){
          e.printStackTrace();
      }
    }
    

    方法二:

    @Component
    public class ParentNode extends Node{
    
      @Autowired
      public void setMongoTemplate(MongoTemplate mongoTemplate){
        ParentNode.mongoTemplate = mongoTemplate;
      }
    
      static private MongoTemplate mongoTemplate;
    
      public void execute(Message message) {
    
      try{
    
          // GET WORKFLOWS COLLECTION
          MongoCollection<Document> collection = mongoTemplate.getCollection("workflows"); 
    
    
      } catch(Exception e){
          e.printStackTrace();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 2013-12-19
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      相关资源
      最近更新 更多