英文:
Mongodb always start with embedded mode in spring boot
问题
我在我的pom文件中添加了以下内容,我只希望在单元测试中使用嵌入式MongoDB。
<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
    <scope>test</scope>
</dependency>
但是即使我以本地模式启动Spring STS,MongoDB始终以嵌入式模式启动,我无法使用数据库客户端连接到它。
对于本地开发测试,我希望连接到在端口27017上运行的本地数据库,如下所示:
spring:
  data:
    mongodb:
      uri: mongodb://localhost:27017/mydb
这是我的MongoConfig类的样子:
@Configuration
@EnableMongoAuditing
public class MongoConfig {
  
    private final MongoProperties mongoProperties;
 
    public MongoConfig(MongoProperties mongoProperties) {
        super();
        this.mongoProperties = mongoProperties;
    }
    //其他bean初始化方法
}
主类只有@SpringBootApplication。
英文:
I have below in my pom, which i only expect embed mongo db with my unit testing.
        <dependency>
			<groupId>de.flapdoodle.embed</groupId>
			<artifactId>de.flapdoodle.embed.mongo</artifactId>
			<scope>test</scope>
		</dependency>
But even when i start Spring STS with local mode, the mongo db always start with embeded mode where i can not connect to it using a db client.
For local dev testing, i expect to connect to my local db runs on post 27017 which i mentioned in my application-local.yml as below,
spring:
  data:
    mongodb:
      uri: mongodb://localhost:27017/mydb
This is what my MongoConfig class looks like,
@Configuration
@EnableMongoAuditing
public class MongoConfig {
  
    private final MongoProperties mongoProperties;
    public MongoConfig(MongoProperties mongoProperties) {
		super();
		this.mongoProperties = mongoProperties;
	}
    //Other bean initialization methods
}
Main class has only @SpringBootApplication
答案1
得分: 0
你在你的pom.xml文件中添加以下依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
然后在你的application.properties文件中添加以下代码:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=db_name
然后你可以像下面这样编写你的模型类:
@Data
@Document(collection = "customer")
public class Customer 
{
  @Id
  private String id;
  
  private String name;
  private String mobile;
}
英文:
You add following dependency in your pom.xml file :
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Then add following code in your application.properties file :
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=db_name
And you write your model class like :
@Data
@Document(collection = "customer")
public class Customer 
{
  @Id
  private String id;
  private String name;
  private String mobile;
}
专注分享java语言的经验与见解,让所有开发者获益!



评论