我想创建一个mongo限制的集合,为此,我在教程中看到需要使用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/**'
}
我需要注入(inject)的类(class):
@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());
    }
}
谢谢

最佳答案

有建议切换到ReactiveMongoOperations。但是由于某种原因,它不会创建上限集合。我切换到Spring Boot 2.2.7.RELEASE版本,它可以正常工作

10-02 00:40