我可以想到两种方法:
1- 仅在 maven 或 gradle 的特定配置文件中加载您的依赖项
Maven
<profiles>
<profile>
<id>local</id>
<dependencies>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>2.0.4-SNAPSHOT</version>
</dependency>
</dependencies>
</profile>
</profiles>
Gradle
if (project.hasProperty('local')) {
dependencies {
compile 'de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.0.4-SNAPSHOT'
}
}
2- 在课堂上使用 @Profile 和 @Import
LoadEmbeded.java
@Profile(value = "local")
@Configuration
@Import(EmbeddedMongoAutoConfiguration.class)
public class LoadEmbeded {
}
希望它能给你一个想法
编辑 1:
我已经测试了我的方法并制作了一个非常简单的应用程序。它适用于@Profile。这是我测试的。
@SpringBootApplication(exclude = EmbeddedMongoAutoConfiguration.class)
public class DemoApplication {
@Autowired
TestRepository repository;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
CommandLineRunner runner() {
return args -> {
System.out.println(repository.save(new Test()));
System.out.println(repository.findAll());
};
}
}
@Repository
interface TestRepository extends MongoRepository<Test, String> {
}
@Document
class Test {
@Id
private String id;
public String getId() {
return id;
}
public Test setId(String id) {
this.id = id;
return this;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("id", id)
.toString();
}
}
@Configuration
@Profile("local")
@Import(EmbeddedMongoAutoConfiguration.class)
class Load {
}
还有application.properties
spring.profiles.active=local
当我将活动配置文件更改为 本地 之外的其他内容时,它会在启动期间引发异常并抱怨 mongodb 的连接。但是当我将其设置为 local 时,它会起作用并向我显示已保存测试实体的 ID。
如果您仍然遇到同样的问题,可能您的依赖项之一正在再次加载嵌入式 MongoDB,即使您将其排除在外。通常它应该带有测试依赖项。检查你的依赖关系。