NullPointerException @Autowired Mongodb collection

孤街醉人 提交于 2020-05-17 06:14:06

问题


I have a configuration class for MongoDB collections as example:

      @Configuration
      public class MongoDBConfiguration{

         @Bean
         public MongoCollection<Document> collection() {


            MongoClient mongoClient = MongoClients.create(mongoURI);
            MongoDatabase database = mongoClient.getDatabase(mongoDatabase);
            return database.getCollection(mongoCollection);
         }
      }

Then I have another class that where I want to use that collection. In this class I get NullPointerException.

    @Component
    public class ExampleClass {

        @Autowired
        private MongoCollection<Document> collection;

        public void getUser(String userID){

                userDoc = collection.find(eq("id", userID)).first();

                /*some other logic*/

        }
    }

And then I have this class where I want to call it.

    @Service
    public class RepeatEvent {

        @Autowired
        MongoCollection<Document> collection;

        @Autowired
        ExampleClass exampleClass;

        @Scheduled(fixedRate = 20000)
        public void repeatEvent() {

            exampleClass.getUser(userID);

            /*some more logic*/

        }
    }

If I use the collection in this last class I don't have a problem but on the ExcampleClass I do. What am I doing wrong?

来源:https://stackoverflow.com/questions/60550899/nullpointerexception-autowired-mongodb-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!