我能够使用以下代码从MongoDB中获取数据,但我想将这些数据从CommandLineRunner运行器公开给其他类。
@Repository
public interface ToolsDao extends MongoRepository< Tools, String> {
public List<Tools> findByRegistries_active(boolean active);
}
此外,我已经编写了与构造方法的getter和setter一样的类。
public class Tools{
@Id
private String id;
private String type;
private List<Registries> registries;
对于注册管理机构,
public class Registries {
private String name;
private String url;
private String secret;
private boolean active;
@Bean
CommandLineRunner runner(ToolsDao toolsDao) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
Registries activeRegistry = null;
Iterable<Tools> toolsList= toolsDao.findByRegistries_active(true);
System.out.println("Configuration : ");
for (Tools tools : toolsList) {
for (Registries registry : config.getRegistries()) {
if(registry.getActive()) {
activeRegistry = registry;
break;
}
}
}
System.out.println("active registry name is " + activeRegistry.getName());
System.out.println("active registry url " + activeRegistry.getRegistryUrl());
}
};
}
我在上面的函数中得到输出,但是如果我想在任何其他函数中使用它,那么它将给出空值。
public class RegistryController2 {
@Autowired
ToolsDao toolsDao;
public Registries getData() {
Registries activeRegistry = null;
Iterable<Tools> personList = toolsDao.findByRegistries_active(true);
System.out.println("Configuration : ");
for (Tools tools : toolsList) {
for (Registries registry : tools.getRegistries()) {
if(registry.getActive()) {
activeRegistry = registry;
break;
}
}
}
System.out.println("active registry name is " + activeRegistry.getName());
System.out.println("active registry url " + activeRegistry.getRegistryUrl());
}
MongoDB数据库:
Given below is MongoDB Collection from database test. and collection name is switchrepo.
"_id" : "1234567890",
"type" : "toolss",
"registreis" : [
{
"name" : "test",
"url" : "test1",
"secret" : "secret",
"active" : true
},
{
"name" : "test2",
"url" : "test12",
"secret" : "secret2",
"active" : false
}
]
}