grpc-ecosystem / grpc-spring

Spring Boot starter module for gRPC framework.

Home Page:https://grpc-ecosystem.github.io/grpc-spring/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

@GrpcClient is null spring boot 3

pdkproitf opened this issue · comments

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?

  • Spring (boot): 3.2.4
  • grpc-java:
  • grpc-client-spring-boot-starter:3.1.0.RELEASE
  • java: version + architecture (64bit?): jdk17-64
  • Other relevant libraries...

Additional context

  • Did it ever work before?
  • Do you have a demo?

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

Screenshot 2024-06-03 at 22 42 03

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

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"));
	}
}

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.

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