【发布时间】: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