简体   繁体   English

在春季启动中如何在多个类中使用@Autowired MongoTemplate

[英]How to use @Autowired MongoTemplate in multiple classes in spring boot

Hi I'm relatively new to spring boot and I'm trying to use the mongotemplate using autowired here's my class 嗨,我是春季引导的新手,我正尝试通过自动装配使用mongotemplate,这是我的课程

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

  @Autowired
  private MongoTemplate mongoTemplate;



  @Override
  public void run(String... strings) throws Exception {
    new Myclass().insert();
  }

This is how my application.yml looks like. 这是我的application.yml的样子。

spring:
  kafka:
    bootstrap-servers: 192.168.155.100:9092
    consumer:
      group-id: foo
  data:
    mongodb:
      host: 192.168.155.100
      port: 27017
      database: test

I am trying to use the mongo template in Myclass and I am calling it from the Test class but the mongotemplate is null. 我试图在Myclass中使用mongo模板,并且从Test类调用它,但是mongotemplate为null。 How should I be doing this? 我应该怎么做? Any help is appreciated 任何帮助表示赞赏

  1. Make MyClass a Bean (annotate the class with @Component or return it from a @Bean method) 使MyClass成为Bean(用@Component注释@Component或从@Bean方法返回它)
  2. Autowire the MyClass bean in that Test class 自动连接该Test类中的MyClass bean
  3. In the run method call insert() on that field. run方法中,对该字段调用insert()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM