grpc-ecosystem / grpc-spring

Spring Boot starter module for gRPC framework.
https://grpc-ecosystem.github.io/grpc-spring/
Apache License 2.0
3.41k stars 808 forks source link

@GrpcClient is null spring boot 3 #1119

Closed pdkproitf closed 1 month ago

pdkproitf commented 1 month ago

The context I'm implementing a gRPC client using 'net.devh:grpc-client-spring-boot-starter:3.0.0.RELEASE'. However, I encountered an error: @GrpcClient is null. I saw some similar issues reported, but they were using an older version, and the workaround solution links are no longer available, so I'm unable to find the solution

The bug

Code:

@Service
public class GrpcClientService {
    @GrpcClient("greeting-grpc-server")
    public GreetServiceGrpc.GreetServiceBlockingStub greetServiceStub;

    public String sendMessage(String name) {
        GreetRequest greetRequest = GreetRequest.newBuilder().setName(name).build();
        GreetResponse greetResponse = this.greetServiceStub.greet(greetRequest);
        return greetResponse.getGreeting();
    }
}

applicaiton.yml

grpc:
  client:
    greeting-grpc-server:
      address: "static://localhost:9090"
      enableKeepAlive: true
      keepAliveWithoutCalls: true

Exception:

Caused by: java.lang.NullPointerException: Cannot invoke "spring_boot.grpc.GreetServiceGrpc$GreetServiceBlockingStub.greet(spring_boot.grpc.GreetRequest)" because "this.greetServiceStub" is null

The application's environment

Which versions do you use?

Additional context

pdkproitf commented 1 month ago

I tried this solution but it still doesn't work.

Screenshot 2024-06-03 at 22 42 03

ST-DDT commented 1 month ago

Do you invoke the constructor of GrpcClientService somewhere or do you let Spring handle that?

pdkproitf commented 1 month ago

hi @ST-DDT thank for your response. i do invoke it when start the application

@SpringBootApplication
@Import(GrpcClientAutoConfiguration.class)
public class GrpcClientApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(GrpcClientApplication.class, args);
        System.out.println("GrpcClientApplication started successfully.");
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("GrpcClientApplication running.");
        GrpcClientService grpcClientService = new GrpcClientService();
        System.out.println(grpcClientService.sendMessage("John"));
    }
}
ST-DDT commented 1 month ago

GrpcClientService grpcClientService = new GrpcClientService();

That line is the issue. Since you create the bean yourself, spring cannot inject anything into it.

You have to use appContext.getBean(GrpcClientService.class) instead.

pdkproitf commented 1 month ago

I see, it works for me. (Spring Boot is still new to me) Thank you so much @ST-DDT