데이터 리졸버 구현
Spring Boot에서 리졸버 함수를 작성해 여러 소스에서 정의한 GraphQL 필드의 데이터를 가져옵니다.
데이터 리졸버 구현은(는) CoddyKit의 무료 GraphQL APIs with Spring Boot 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 GraphQL APIs with Spring Boot 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What are Data Resolvers?
Welcome! In GraphQL, clients ask for specific data. But how does your server know where to get that data?
That's where Data Resolvers come in! A resolver is a function or method that knows how to fetch the data for a specific field in your GraphQL schema.
- They act as the bridge between your schema and your data sources (like databases, APIs, or even simple in-memory lists).
- Each field in your schema needs a resolver, implicitly or explicitly.
Resolvers in Spring for GraphQL
Spring for GraphQL makes implementing resolvers straightforward. It uses annotations to map Java methods directly to fields in your GraphQL schema.
You'll typically write these resolver methods inside Spring @Controller classes. Spring automatically scans these controllers and connects their methods to the GraphQL schema fields based on naming conventions or explicit annotations.
Your First Root Query Resolver
Let's create a simple resolver for a root query. We'll define a basic hello field that returns a greeting string.
First, imagine our schema has:
type Query {
hello: String
}Now, let's write the Java resolver:
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
@Controller
public class GreetingController {
@QueryMapping
public String hello() {
return "Hello from CoddyKit!";
}
}Resolving Custom Objects
Resolvers aren't just for simple strings. They can return custom Java objects too! Let's define a simple Book class and a resolver to return it.
Assume our schema has:
type Book {
id: ID
title: String
author: String
}
type Query {
firstBook: Book
}Here's the Book class and a resolver:
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
// A simple data class for our Book
record Book(String id, String title, String author) {}
@Controller
public class BookController {
@QueryMapping
public Book firstBook() {
return new Book("book-1", "The Great Journey", "Alice Wonderland");
}
}Mocking Data Sources
For our examples, we won't connect to a real database. Instead, we'll use an in-memory list to simulate a data source. This keeps our code simple and focused on resolvers.
In a real application, your resolvers would interact with:
- Databases (SQL, NoSQL)
- Other REST or GraphQL APIs
- Message queues
- File systems
The resolver's job is just to get the data, no matter the source!
Implementing a List Resolver
Often, you'll want to return a list of objects. Our BookController can be updated to provide a list of books from a mock source.
If our schema has:
type Query {
allBooks: [Book]
}Here's how we'd implement the resolver:
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
import java.util.List;
import java.util.ArrayList;
record Book(String id, String title, String author) {}
@Controller
public class BookListController {
private final List<Book> books = new ArrayList<>(List.of(
new Book("b-1", "The Moonstone", "Wilkie Collins"),
new Book("b-2", "Pride and Prejudice", "Jane Austen"),
new Book("b-3", "1984", "George Orwell")
));
@QueryMapping
public List<Book> allBooks() {
return books;
}
}Resolving by ID with Arguments
Queries often need arguments, like searching for a book by its ID. Resolvers can easily accept these arguments.
If our schema has:
type Query {
bookById(id: ID!): Book
}We use the @Argument annotation in Spring for GraphQL:
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
import java.util.List;
import java.util.ArrayList;
record Book(String id, String title, String author) {}
@Controller
public class BookByIdController {
private final List<Book> books = new ArrayList<>(List.of(
new Book("b-1", "The Moonstone", "Wilkie Collins"),
new Book("b-2", "Pride and Prejudice", "Jane Austen")
));
@QueryMapping
public Book bookById(@Argument String id) {
return books.stream()
.filter(book -> book.id().equals(id))
.findFirst()
.orElse(null);
}
}Field-Level Resolvers
Sometimes, a field on an object itself needs a separate resolver. For example, if the author of a Book was a complex object needing its own lookup.
Let's say Book has an authorId, and we need to fetch the full Author object. We use @SchemaMapping for these non-root fields.
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.stereotype.Controller;
record Book(String id, String title, String authorId) {}
record Author(String id, String name) {}
@Controller
public class AuthorResolver {
// This resolver is for the 'author' field on a 'Book' object
@SchemaMapping
public Author author(Book book) {
// In a real app, you'd fetch from a data source using book.authorId()
if ("auth-1".equals(book.authorId())) {
return new Author(book.authorId(), "Wilkie Collins");
}
return new Author(book.authorId(), "Unknown Author");
}
}Complete Resolver Application
Let's put everything together into a runnable Spring Boot application! This example includes resolvers for listing books, finding a book by ID, and resolving an author for a book.
Try running this and querying it with a GraphQL client!
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.stereotype.Controller;
import java.util.List;
import java.util.ArrayList;
// Data classes
record Book(String id, String title, String authorId) {}
record Author(String id, String name) {}
@SpringBootApplication
public class GraphQLResolversApp {
public static void main(String[] args) {
SpringApplication.run(GraphQLResolversApp.class, args);
}
}
@Controller
class BookDataController {
private final List<Book> books = new ArrayList<>(List.of(
new Book("b-1", "The Moonstone", "auth-1"),
new Book("b-2", "Pride and Prejudice", "auth-2"),
new Book("b-3", "1984", "auth-3")
));
@QueryMapping
public List<Book> allBooks() {
return books;
}
@QueryMapping
public Book bookById(@Argument String id) {
return books.stream()
.filter(book -> book.id().equals(id))
.findFirst()
.orElse(null);
}
// Field-level resolver for 'author' on 'Book'
@SchemaMapping
public Author author(Book book) {
// Mocking author data lookup
return switch (book.authorId()) {
case "auth-1" -> new Author("auth-1", "Wilkie Collins");
case "auth-2" -> new Author("auth-2", "Jane Austen");
case "auth-3" -> new Author("auth-3", "George Orwell");
default -> new Author(book.authorId(), "Unknown Author");
};
}
}Understanding Resolver Mapping
Which of the following statements about GraphQL resolvers in Spring Boot are TRUE?
Recap: Your Resolver Journey
You've taken a big step in building GraphQL APIs!
- We learned that resolvers are the core logic for fetching data.
- Spring for GraphQL uses
@Controllerwith@QueryMappingfor root queries and@SchemaMappingfor nested fields. - Resolvers can return simple types, custom objects, and lists.
- You can pass arguments to resolvers using the
@Argumentannotation.
Next, you'll learn how to execute these queries using tools like GraphiQL!
자주 묻는 질문
“데이터 리졸버 구현” 강의는 무료인가요?
네 — “데이터 리졸버 구현” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 GraphQL APIs with Spring Boot 강의 전체를 잠금 해제할 수 있습니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.
“데이터 리졸버 구현”에서 뭘 배우나요?
Spring Boot에서 리졸버 함수를 작성해 여러 소스에서 정의한 GraphQL 필드의 데이터를 가져옵니다. 브라우저에서 직접 실행하는 실습 코드로 GraphQL APIs with Spring Boot을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
GraphQL APIs with Spring Boot을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 GraphQL APIs with Spring Boot은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“데이터 리졸버 구현” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 GraphQL APIs with Spring Boot 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 GraphQL APIs with Spring Boot 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.