我在VM上设置了MongoDB。现在,我需要使用SpringBoot从本地计算机连接到Mongo(托管在VM上)。有了虚拟机的用户名,密码和IP地址,我应该如何更改application.propeties文件。
如何为下面的InitDatabase
类在VM中设置Mongo
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Component;
@Component
public class InitDatabase {
@Bean
CommandLineRunner init(MongoOperations operations) {
return args -> {
operations.dropCollection(Image.class);
operations.insert(new Image("1",
"learning-spring-boot-cover.jpg"));
operations.insert(new Image("2",
"learning-spring-boot-2nd-edition-cover.jpg"));
operations.insert(new Image("3",
"bazinga.png"));
operations.findAll(Image.class).forEach(image -> {
System.out.println(image.toString());
});
};
}
}
答案 0 :(得分:1)
您应该覆盖spring.mongodb配置属性:
spring.data.mongodb.authentication-database= *which_authentication_database_you_want_to_connect*
spring.data.mongodb.username=*database_username*
spring.data.mongodb.password=*database_password*
spring.data.mongodb.database=*which_database_you_want_to_connect*
spring.data.mongodb.port=*running_mongo_instance_port*
spring.data.mongodb.host=*running_mongo_instance_host -- you should write your own VM's ip address*