0

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?

jpdoliveira
  • 15
  • 10
  • How are you getting the instance of `ExampleClass` when you get NPE ? Please share that code as well – R.G Mar 06 '20 at 01:35
  • @R.G Doesn't the annotation Service, Component, Configuration create beans in the Spring context? Making the Autowired ExampleClass exampleClass enough? – jpdoliveira Mar 06 '20 at 11:43
  • @jpdoliveiraThe `ExampleClass` should also be a bean obtained from application context. Spring takes care of wiring the `MongoCollection` in that case. If the `ExampleClass` instance was created with the `new` keyword , it is not a spring managed bean and an NPE is expected. – R.G Mar 06 '20 at 12:13
  • This answer in another topic solved the problem: https://stackoverflow.com/a/18486178/12398027 – jpdoliveira Mar 06 '20 at 15:41
  • And the issue was ? – R.G Mar 06 '20 at 15:48
  • An `@Autowired` field cannot be `null`. It can only be `null` if you are creating an instance of that bean yourself outside the scope of spring. Or if this isn't the actual code and you have a final (or private) method on a class that is being proxied, which might appear as if it was `null`. – M. Deinum Mar 26 '20 at 16:01

0 Answers0