【发布时间】:2020-10-22 19:23:43
【问题描述】:
我想创建一个 mongo capped 集合,为此,我在教程中看到我需要使用 MongoOperations bean。但我不能自动接线。
说明:
com.daimon.reactivespring.initialize.ItemDataInitializer 中构造函数的参数 1 需要一个无法找到的 'org.springframework.data.mongodb.core.MongoOperations' 类型的 bean。
行动:
考虑在你的配置中定义一个“org.springframework.data.mongodb.core.MongoOperations”类型的bean。
build.gradle:
plugins {
id 'org.springframework.boot' version '2.3.1.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.daimon.reactivespring'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'de.flapdoodle.embed:de.flapdoodle.embed.mongo'
testImplementation 'io.projectreactor:reactor-test'
}
test {
useJUnitPlatform()
exclude 'com/daimon/reactivespring/fluxmono/**'
}
我需要注入的类:
@Component
@RequiredArgsConstructor
@Profile("!test")
public class ItemDataInitializer implements CommandLineRunner {
//@Autowired
private final ItemReactiveRepository itemReactiveRepository;
//@Autowired
private final MongoOperations mongoOperations;
@Override
public void run(String... args) throws Exception {
initialDatSetup();
createCappedCollection();
}
private void initialDatSetup() {
itemReactiveRepository.deleteAll()
.thenMany(Flux.fromIterable(initItems()))
.flatMap(itemReactiveRepository::save)
.subscribe(item -> System.out.println("Item inserted " + item));
}
private List<Item> initItems() {
return Arrays.asList(new Item(null, "Samsung TV", 200.0),
new Item(null, "Apple TV", 300.0), new Item(null, "LG TV", 400.0));
}
private void createCappedCollection() {
mongoOperations.dropCollection(ItemCapped.class);
mongoOperations.createCollection(ItemCapped.class, CollectionOptions.empty().maxDocuments(20).size(50000).capped());
}
}
谢谢
【问题讨论】:
-
你正在混合反应和阻塞的东西。没有反应性
MongoOperations。您将不得不使用反应式ReactiveMongoOperations。 -
你能告诉我们你的spring boot主类,mongodb应用程序属性吗?看看你的类路径,你的类路径上有 spring-boot-autoconfigure 吗?
标签: java spring mongodb spring-boot gradle