Use a single MongoClient across a JavaEE web service

前端 未结 2 1790
挽巷
挽巷 2021-01-12 13:34

After reading the mongo documentation that says each instance of a MongoClient handles its own pooling, how would I go about only having one instance across my whole applica

2条回答
  •  情深已故
    2021-01-12 14:10

    Since you are in a java ee environment, the best way to implement this would be to use CDI producers:

    @Stateless
    public class ConnetionFactory {
    
      @ApplicationScoped
      @Produces
      public MongoClient mongoClient() {
        return new MongoClient();
      }
    }
    

    Then in every bean you want to use it in:

    @Stateless
    public class MyServiceBean {
    
      @Inject
      private MongoClient mongoClient;
    }
    

提交回复
热议问题