You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在io.grpc创建的gRPC端点中使用@Autowired实现依赖注入

解决方案:gRPC服务类Spring依赖注入失败问题

问题根源

你直接通过new CartPurchaseQueryImpl()创建服务类实例,这个对象不在Spring容器的管理范围内,因此Spring无法为其注入CategoryProductRepository,导致依赖始终为空。

修复步骤

1. 修改启动类,注入Spring管理的gRPC服务实例

将启动类中手动new的服务实例替换为Spring注入的Bean,让Spring容器完成依赖注入:

@SpringBootApplication
public class CartPurchaseQueryApplication implements ApplicationRunner {

    // 注入Spring管理的CartPurchaseQueryImpl实例
    @Autowired
    private CartPurchaseQueryImpl cartPurchaseQueryImpl;

    public static void main(String[] args) {
        SpringApplication.run(CartPurchaseQueryApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws InterruptedException, IOException {
        SocketAddress address = new InetSocketAddress("springboot", 30010);
        Server server = NettyServerBuilder.forAddress(address)
                // 使用Spring注入的实例,而非手动new
                .addService(cartPurchaseQueryImpl)
                .intercept(new JWTInterceptor())
                .build();

        server.start();
        server.awaitTermination();
    }
}

2. 确保依赖类也被Spring管理

确认CategoryProductRepository已被Spring识别并管理,比如添加@Repository注解:

@Repository
public interface CategoryProductRepository extends JpaRepository<...> {
    // 你的仓库方法
}

额外优化(可选)

如果JWTInterceptor也需要Spring注入依赖,同样不要手动new,改为注入方式:

@Autowired
private JWTInterceptor jwtInterceptor;

// 构建server时使用注入的拦截器
.intercept(jwtInterceptor)

核心原理

只有由Spring容器创建和管理的Bean,Spring才会自动完成@Autowired、@Resource等注解的依赖注入操作。手动new的对象脱离了Spring的管理生命周期,自然无法触发注入逻辑。

内容的提问来源于stack exchange,提问作者Rafael Souza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 12:17:22