gpt4 book ai didi

java - Spring Boot Data MongoDB - 存储库为空

转载 作者:行者123 更新时间:2023-12-01 09:17:05 26 4
gpt4 key购买 nike

我想使用 Spring Boot 和 Spring Data MongoDB 开发一个小测试应用程序。因此,在本例中,我使用默认配置(例如 localhost:27017/test 数据库),并尝试遵循 spring 指南 ( https://spring.io/guides/gs/accessing-data-mongodb/ )。

我像这样启动我的应用程序:

@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();
}
}

DummyClass如下:

@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);
}
}

当执行projectRepository.deleteAll()语句时,我收到un NullPointerException。

有关信息,请参见 ProjectRepository 界面下方:

public interface ProjectRepository extends MongoRepository<Project, String>     
{
}

我的包结构是: com.test.dummy 应用程序.java com.test.dummy.components DummyClass.java com.test.dummy.domain 项目.java com.test.dummy.repositories 项目存储库.java

你能帮我理解我的错误吗?

注意:我使用 Spring Boot 1.4.1 和 Mongo 3.2

最佳答案

Application.run() 方法中,您在 Spring 上下文之外实例化 DummyClass (new DummyClass())。这样就可以了

@Autowired
private ProjectRepository projectRepository;

未正确实例化。

您应该通过 Spring 注入(inject) DummyClass,而不是通过其构造函数创建它的新实例。

示例:

@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();
}
}

关于java - Spring Boot Data MongoDB - 存储库为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40467531/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com