如何在spring boot中的多个类中使用@Autowired MongoTemplate

时间:2018-06-01 19:40:15

标签: java mongodb spring-boot autowired mongotemplate

嗨,我对春季靴子相对较新,我正在尝试使用mongotemplate 使用autowired这里是我的班级

@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();
  }

这就是我的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

我正在尝试在Myclass中使用mongo模板,我从Test类调用它,但是mongotemplate为null。我该怎么做?任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

  1. 将MyClass设为Bean(使用@Component注释该类或使用@Bean方法返回)
  2. MyClass
  3. 中自动装配Test bean
  4. 在该字段的run方法调用insert()中。
相关问题