Spring Boot中GraphQLSchema Bean未自动注册问题求助
Let’s break down the common reasons you’re hitting this error and walk through how to fix them:
1. Dependency Version Mismatch
The most frequent culprit here is incompatible versions between graphql-spring-boot-starter, graphql-java-tools, and your Spring Boot version. These libraries have tight version constraints—mixing mismatched versions can break the auto-configuration that’s supposed to create the GraphQLSchema bean automatically.
Double-check that your dependencies align with your Spring Boot version. For example, if you’re using Spring Boot 2.7.x, stick to a compatible release of the GraphQL starters (avoid mixing major versions).
2. Incorrect GraphQL Schema File Location
By default, graphql-java-tools looks for .graphqls files in the root of your classpath (i.e., src/main/resources/). If you’ve placed your schema files in a subdirectory (like src/main/resources/graphql/), you need to explicitly tell the tools where to find them by adding this property to application.properties:
graphql.tools.schema-location-pattern=graphql/*.graphqls
Adjust the pattern to match your actual file structure—wildcards work if you have multiple schema files.
3. Missing Resolver/DataFetcher Classes
The auto-generated GraphQLSchema relies on having resolver classes that map to the queries/mutations defined in your .graphqls file. For example:
- If your schema has a query like:
type Query { getBook(id: ID!): Book } - You need a corresponding resolver class (annotated with
@Componentor@Serviceso Spring can detect it):@Component public class BookQueryResolver implements GraphQLQueryResolver { public Book getBook(String id) { // Your data fetching logic here } }
Without these resolvers, graphql-java-tools can’t build a valid executable schema, so the GraphQLSchema bean won’t be created.
4. Disabled Auto-Configuration
Ensure your Spring Boot application hasn’t excluded the GraphQL auto-configuration classes. Your main application class should have @SpringBootApplication (which includes @EnableAutoConfiguration by default)—avoid adding exclude attributes that might block the GraphQL auto-config.
Do You Need to Define the GraphQLSchema Bean Explicitly?
In most cases, no—if the above steps are correct, the starter should create the bean automatically. However, if auto-configuration fails for an edge case, you can define it manually as a last resort:
@Configuration public class GraphQLConfig { @Bean public GraphQLSchema graphQLSchema(SchemaParser schemaParser, TypeDefinitionRegistry typeDefinitionRegistry, RuntimeWiring runtimeWiring) { return schemaParser.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring); } }
Start with verifying your resolver classes and schema file location first—those are the most common fixes for this error.
内容的提问来源于stack exchange,提问作者Atul Ojha

