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
Applicationclass extendingSpringBootServletInitializer? Second, please show the code you are using for your custom utility classstaticfield you are trying to inject). Also in your configuration you can remove@EnableMongoRepositoriesand@Import(RepositoryRestMvcConfiguration.class), Spring Boot automatically adds those when respective Spring Data MongoDB and Spring Data Rest is detected. In addition if yourApplicationclass is in thecom.khoubyari.examplepackage you can just do@ComponentScan.