I want to develop a little test application using Spring Boot and Spring Data MongoDB. So, in this case, I use default configuration (like localhost:27017/test database) and I try to follow the spring guide ( https://spring.io/guides/gs/accessing-data-mongodb/ ).
I launch my application like this:
@SpringBootApplication
public class Application implements CommandLineRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... strings) throws Exception {
(new DummyClass()).load();
}
}
The DummyClass is as following:
@org.springframework.stereotype.Component
@ConfigurationProperties(prefix="dummy")
public class DummyClass {
private static String url;
private List<Project> projects;
@Autowired
private ProjectRepository projectRepository;
public void setUrl(String url) {
DummyClass.url = url;
}
@Override
public void load() {
// (...) creating some project objects
projectRepository.deleteAll();
projectRepository.save(this.projects);
}
}
When the projectRepository.deleteAll() statement is executed, I receive un NullPointerException.
For information, below the ProjectRepository interface:
public interface ProjectRepository extends MongoRepository<Project, String>
{
}
And my package structure is: com.test.dummy Application.java com.test.dummy.components DummyClass.java com.test.dummy.domain Project.java com.test.dummy.repositories ProjectRepository.java
Can you help me to understand my error?
Note: I use Spring Boot 1.4.1 and Mongo 3.2
Inside your Application.run()
method you instantiate your DummyClass outside of the Spring context ( new DummyClass()
). This way the
@Autowired
private ProjectRepository projectRepository;
is not instantiated correctly.
You should inject your DummyClass
via Spring and not create a new instance of it via its constructor.
Example:
@SpringBootApplication
public class Application implements CommandLineRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
@Autowired
DummyClass dummyClass;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... strings) throws Exception {
dummyClass.load();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.