如何获取已配置的ExecutionGraphQlService实例引用?
在Spring Boot Spring GraphQL项目中获取ExecutionGraphQlService引用
在Spring Boot配置的Spring GraphQL项目里,ExecutionGraphQlService是由框架自动配置并注册到Spring容器中的bean,你可以通过以下方式获取它的引用:
1. 依赖注入(推荐方式)
在任何Spring管理的组件(比如@Component、@Service、@Controller等标注的类)中,通过构造函数注入、@Autowired字段注入或者@Setter注入来获取实例,其中构造函数注入是Spring官方推荐的方式:
构造函数注入示例
import org.springframework.graphql.execution.ExecutionGraphQlService; import org.springframework.stereotype.Service; @Service public class ServerGraphQlQueryService { private final ExecutionGraphQlService executionGraphQlService; // 构造函数注入,Spring会自动匹配容器中的ExecutionGraphQlService实例 public ServerGraphQlQueryService(ExecutionGraphQlService executionGraphQlService) { this.executionGraphQlService = executionGraphQlService; } // 示例:执行GraphQL查询的方法 public void executeServerSideQuery(String query) { // 构建GraphQL请求并执行 // 例如: // ExecutionInput input = ExecutionInput.newExecutionInput().query(query).build(); // executionGraphQlService.execute(input).subscribe(...); } }
字段注入示例(兼容旧代码,不推荐)
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.graphql.execution.ExecutionGraphQlService; import org.springframework.stereotype.Component; @Component public class LegacyGraphQlExecutor { @Autowired private ExecutionGraphQlService executionGraphQlService; // 使用executionGraphQlService执行查询逻辑 }
2. 通过ApplicationContext获取(特殊场景使用)
如果需要在非Spring托管的类中获取实例,可以通过ApplicationContext的getBean方法获取,但这种方式会破坏依赖注入的解耦性,仅在必要场景下使用:
import org.springframework.context.ApplicationContext; import org.springframework.graphql.execution.ExecutionGraphQlService; public class NonSpringManagedClass { public void getExecutionService(ApplicationContext context) { ExecutionGraphQlService executionGraphQlService = context.getBean(ExecutionGraphQlService.class); // 后续使用逻辑 } }
注意事项
- 确保项目中已经引入
spring-boot-starter-graphql依赖,Spring Boot才会自动配置ExecutionGraphQlServicebean。 - 如果自定义了GraphQL相关配置,只要没有覆盖自动配置的
ExecutionGraphQlService实例,上述注入方式依然有效。
内容的提问来源于stack exchange,提问作者bjlevine
相关产品推荐
相关产品推荐

