【问题标题】:How to use @Autowired MongoTemplate in multiple classes in spring boot如何在spring boot的多个类中使用@Autowired MongoTemplate
【发布时间】:2018-11-11 23:43:41
【问题描述】:

嗨,我对 Spring Boot 比较陌生,我正在尝试使用 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 为空。我应该怎么做?任何帮助表示赞赏

【问题讨论】:

  • 你也使用了@Configuration注解吗?
  • 我应该在我的主课还是我正在调用的课上使用它

标签: java mongodb spring-boot autowired mongotemplate


【解决方案1】:
  1. 使 MyClass 成为 Bean(使用 @Component 注释类或从 @Bean 方法返回它)
  2. Test 类中自动装配 MyClass bean
  3. 在该字段的run 方法调用insert()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2017-03-02
    • 1970-01-01
    • 2021-10-07
    相关资源
    最近更新 更多