No instance(s) of type variable(s) T exist so that

2019-08-25 02:38发布

问题:

I am implementing Spring webflux demo application and have written my demo application as like that

package com.abcplusd.application;

import com.abcplusd.domain.Event;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.Collections;
import java.util.Date;
import java.util.stream.Stream;

@SpringBootApplication
public class ReactiveClientApplication {

    @Bean WebClient webClient() {
        return WebClient.create("http://localhost:8080");
    }

    @Bean CommandLineRunner demo(WebClient webClient) {
        return args -> {
            webClient.get()
                .uri("/events")
                .accept(MediaType.TEXT_EVENT_STREAM)
                .exchange()
                .flatMap(clientResponse -> clientResponse.bodyToFlux(Event.class))
                .subscribe(System.out::println);
        };
    }
    public static void main(String[] args) {
        new SpringApplicationBuilder(ReactiveClientApplication.class)
            .properties(Collections.singletonMap("server.port", "8081"))
            .run(args);
    }
}

It shows the following error

Error:(29, 41) java: incompatible types: no instance(s) of type variable(s) T exist so that reactor.core.publisher.Flux<T> conforms to reactor.core.publisher.Mono<? extends R>

The above error is at this line:

                    .flatMap(clientResponse -> clientResponse.bodyToFlux(Event.class)))

Event Class

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Date;

@Data
@AllArgsConstructor
public class Event {
    private  long id;
    private Date when;
}

Can anybody help me to solve the error?

回答1:

It works me after i have done these changes in my code

.flatMap(clientResponse -> clientResponse.bodyToFlux(Event.class))) 

to

.flatMapMany(clientResponse -> clientResponse.bodyToFlux(Event.class))

and

@NoArgsConstructor annotation in Event.Class

as follows:

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Event {
    private  long id;
    private Date when;

}


回答2:

flatMapMany instead of flatMap works.

However when you add property spring.main.web_environment=false to application.properties file, webClient simply doesn't work.