spring data mongodb configuration in spring boot based project
Calling save method in spring rest controller resolved the issue in stead of calling from utility class.
I just inject CustomRepository interface in controller and using save method!
I got the solution after studying "About the Service" section from https://github.com/khoubyari/spring-boot-rest-example
I need to explore more in spring boot but anyways problem is resolved after above posted efforts!
S Singh
Updated on June 05, 2022Comments
-
S Singh almost 2 years
I am writing code with spring boot which will take csv as input and create mongodb collection and insert it to mongodb.
Currently I am sticking in using mongodb in spring boot based code. I am getting NullPointerException while using save method on MongoRepository interface.
Probably this problem is due to incorrect configuration in application.yml file Below is mongodb specific changes in application.yml in src/main/resources directory.
spring: data: mongodb.host: localhost mongodb.port: 27017 mongodb.uri: mongodb://localhost/test mongo.repositories.enabled: true
Application.java file is below:
@Configuration @EnableMongoRepositories @Import(RepositoryRestMvcConfiguration.class) @EnableAutoConfiguration // Sprint Boot Auto Configuration @ComponentScan(basePackages = "com.khoubyari.example") public class Application extends SpringBootServletInitializer { private static final Class<Application> applicationClass = Application.class; private static final Logger log = LoggerFactory.getLogger(applicationClass); public static void main(String[] args) { SpringApplication.run(applicationClass, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(applicationClass); } }
If Application.java implements CommandLineRunner and write mongodb insertion specific code in overrided method run, code is working fine. This code is available in this URL: https://spring.io/guides/gs/accessing-data-mongodb/
but, my Application.java extends SpringBootServletInitializer class and override configure(SpringApplicationBuilder application) method. Please look at above for my Application.java.
I need to use same db specific code (as in same code for which URL I mentioned above in Application.java class) in utility class existing in different package for my spring boot based project.
Custom repository interface is below:
CustomRepository.java: public interface CustomRepository extends MongoRepository<CsvPojo, String>{ }
In utility class, I just want to inject CustomRepository and use save method to save created CsvPojo in mongodb. But I am geiing NullPointerException while executing line customRepository.save(csvPojo);
Please suggest! If other information is needed, please tell me!
Regards, Shobhit