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?