SpringBoot集成GRPC时repository注入为空问题求助
SpringBoot集成gRPC时Autowired注入Repository为空的解决方案
出现Can not invoke this.repository.methodname because this.repository is null的核心原因是你的gRPC实现类personDetailImpl未被Spring容器管理,导致Spring无法自动注入Repository实例。以下是具体解决步骤:
1. 将gRPC实现类纳入Spring容器管理
在personDetailImpl类上同时添加@GrpcService(用于注册gRPC服务)和@Service/@Component注解,确保Spring能扫描并创建该类的实例:
@GrpcService @Service public class PersonDetailImpl extends PersonDetailGrpc.PersonDetailImplBase { @Autowired private PersonRepository repository; // 实现gRPC服务方法 @Override public void getPersonDetail(PersonRequest request, StreamObserver<PersonResponse> responseObserver) { // 调用Repository方法 Person person = repository.findById(request.getId()).orElse(null); // 构建并返回响应 PersonResponse response = PersonResponse.newBuilder() .setId(person.getId()) .setName(person.getName()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } }
2. 禁止手动实例化gRPC实现类
绝对不要用new PersonDetailImpl()的方式创建实例,必须由Spring容器提供实例。若需在其他类中引用该gRPC实现类,同样通过@Autowired注入。
3. 确保Repository被Spring正确扫描
- 在Repository接口上添加
@Repository注解:@Repository public interface PersonRepository extends JpaRepository<Person, Long> { // 自定义查询方法 } - 检查启动类的
@SpringBootApplication注解是否覆盖了Repository所在包,若未覆盖则手动添加@EnableJpaRepositories指定包路径:@SpringBootApplication @EnableJpaRepositories(basePackages = "com.yourproject.repository") public class GrpcApplication { public static void main(String[] args) { SpringApplication.run(GrpcApplication.class, args); } }
4. 推荐使用构造器注入替代@Autowired
构造器注入可避免空指针问题,同时符合Spring最佳实践(Spring 4.3+无需额外添加@Autowired):
@GrpcService public class PersonDetailImpl extends PersonDetailGrpc.PersonDetailImplBase { private final PersonRepository repository; // 构造器注入 public PersonDetailImpl(PersonRepository repository) { this.repository = repository; } // gRPC方法实现... }
内容的提问来源于stack exchange,提问作者Sku
相关产品推荐
相关产品推荐

