Source: www.toutiao.com/i6929867921…

preface

This article provides a basic example of how to quickly use a Web project based on Spring Boot.

GraphQL-Java Getting Started with GraphQL Java and Spring Boot provides dependencies for quick configuration, but I really don’t recommend using this library and its associated configuration for scaffolding. As a result, more and more business code needs to be configured. Compared with the following method, the code complexity is higher.

This article provides a more flexible and fast way to quickly develop applications in Spring Boot projects. The dependency of use is also different from that provided by the above official, please pay attention to distinguish.

Quick start

Create a Spring Boot project

Through Spring Initializr quick build, I selected JDK version and Spring Boot version, as shown below, other versions have not been tested for compatibility.

Click on the Generate button below:

I deleted application.properties and replaced it with Applicaton.yml because I personally prefer yamL configuration:

Introducing dependent dependencies

The pom.xml configuration is as follows:

<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.4.6 < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <groupId>com.xuxd</groupId> <artifactId>graphql.demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name> Graphql. demo</name> <description>GraphQL Demo project for Spring Boot < / description > < properties > < Java version > 1.8 < / Java version > < maven.com piler. Source > 1.8 < / maven.com piler source > < maven.com piler target > 1.8 < / maven.com piler. Target > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > The < project. Reporting. OutputEncoding > utf-8 < / project. Reporting. OutputEncoding > < lombok. Version > 1.18.20 < / lombok. Version > < graphql - Java - view version > 11.0.1 < / graphql - Java - view version > < gson. Version > 2.8.7 < / gson version > < / properties > <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId>  <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.graphql-java-kickstart</groupId> <artifactId>graphql-java-tools</artifactId> <version>${graphql-java-tools.version}</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>${gson.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>Copy the code

Initialize the GraphQL instance

We’ll create a GraphQL instance and register it with the Spring container as follows:

Create a GraphQLProvider class:

@Component public class GraphQLProvider { private GraphQL graphQL; @Autowired private IItemService itemService; @Bean public GraphQL graphQL() { return graphQL; } @PostConstruct public void init() throws IOException { GraphQLSchema graphQLSchema = SchemaParser.newParser() .file("graphql/base.graphqls") .resolvers(new Query(), new Mutation()) .file("graphql/item.graphqls") .resolvers(new ItemResolver(itemService)) // .file("book.graphqls") // .resolvers(new BookResolver()) // Other definitions continue to add.build().makeexecutableschema () as shown above; this.graphQL = graphQL.newGraphQL(graphQLSchema).build(); }}Copy the code

*.graphqls and its corresponding Resolver, ItemResolver, can be seen in the GraphQL description.

base.grqphqls

Schema {# mutation: mutation} type query {version: String} type mutation {version: String}Copy the code

item.graphqls

Extend type Query {queryItemList: ItemList queryById(id: id): Item} extend type Mutation {updateName(param: param): Item} code: String! name: String! } type ItemList { itemList: [Item!] ! Total: Int! } input Param {id: id! name: String! }Copy the code

ItemResolver

public class ItemResolver implements GraphQLQueryResolver, GraphQLMutationResolver { private IItemService itemService; public ItemResolver(IItemService itemService) { this.itemService = itemService; } / / corresponding item graphqls queryItemList in public ItemList queryItemList () {return itemService. QueryItemList (); } public Item queryById(Long id) { return itemService.queryById(id); } public Item updateName(Param param) { return itemService.updateName(param); }}Copy the code

More relevant business code, not a paste.

Provides the API

We need to expose an interface to receive the request and do the relevant processing, and we only need to provide one interface. So we create a Controller: GraphqlController.

@RestController @RequestMapping("/graphql") @Log public class GraphqlController { @Autowired private GraphQL graphQL; @PostMapping public Object execute(@RequestBody GraphqlRequest request) { ExecutionInput executionInput = ExecutionInput.newExecutionInput() .query(request.getQuery()) .variables(request.getVariables()) .build(); Map<String, Object> result = new HashMap<>(); ExecutionResult executionResult = graphQL.execute(executionInput); List<GraphQLError> errors = executionResult.getErrors(); if (errors ! = null && ! errors.isEmpty()) { result.put("errors", errors); return result; } return executionResult.getData(); }}Copy the code

At this point, the basic functionality has been configured and you are ready to launch the project for testing.

The code structure of the whole project is as follows. I try to use a more conventional Web project structure (controller, Service, DAO, etc.) :

test

A total of 3 interfaces are provided in the example, with two queries and one update tested separately:

ItemList queryItemList();

Item queryById(Long id);

Item updateName(Param param);
Copy the code

Query all item lists (just get the code and name of each item, and the total number of lists) :

Query by ID to get the ID and name of the project

Updates the project name with the specified ID

Our project with Id 1 and code test is changed to “Java project”

Query again and see that the result is updated:

conclusion

The basic configuration of the GraphQL for the whole project is now complete and ready for business development.

Recent hot articles recommended:

1.1,000+ Java Interview Questions and Answers (2021)

2. Don’t use if/ else on full screen again, try strategy mode, it smells good!!

3. Oh, my gosh! What new syntax is xx ≠ null in Java?

4.Spring Boot 2.5 is a blockbuster release, and dark mode is exploding!

5. “Java Development Manual (Songshan version)” the latest release, quick download!

Feel good, don’t forget to click on + forward oh!