Spring boot with mongoDB returns NullPointerException

890 views Asked by At

Recently, I was trying to play with MongoDB and Spring Boot.

I've seen multiple tutorials on how to do it, but I faced a problem when I tried to insert an object to the database. The issue is that, every tutorial or answer provided in SO implied that I will call the Repository that extends the MongoRepo through a REST Function (and as a Result the @Autowire annotation will instantiate the class). However, this is not the case for my program, as I will need to call the store class through a class located in a different package that is not being called via a REST API. The first issue was with the scan of the different packages.I managed to solve it by using the baseScanPackages and the @EnableMongoRepository annotation. I also created the MongoConfig class as the latter needed the MongoClient implementation.

However, every time I call the class that stores my object, I get a NullPointerException. I know that the problem is that ,since I call the class via a new Object and not Autowire it, the interface will not be instantiated.

My question is: Is there a way I can instantiate the interface that extends the MongoRepository without having to Autowire it?

Below is the code:

Interface

@Repository
public interface TemplateRepository extends MongoRepository<Template,String> {
}

Store class

@Component
public class StoreTemplates {

    \\The issue is here. This class is never instantiated.
    private TemplateRepository templateRepository;
    @Autowired
    public StoreTemplates(TemplateRepository templateRepository) {
        this.templateRepository=templateRepository;
    }

    public void store(Template template){

        if(templateRepository!=null)
            templateRepository.save(template);
        else
            System.out.println("not initialised");
    }
}

Constructor of the class that calls the save method

StoreTemplates storeTemplates;
    /**
     * Constructor.
     * 
     * @param connection
     */
    public TemplateGeneral(Connection connection) {
        super(connection);
        storeTemplates = new StoreTemplates(); <- This will not trigger the @Autowired class
    }

Thank you!

1

There are 1 answers

0
Niraj Jha On

Last piece of code is incorrect where Instantiation is done via new keyword. Until or unless you won't allow spring to do the injection which is the main purpose of using spring. I don't see any way to get it directly.