當前端應用跨多端時,常碰到的問題有:前端
爲了解決這些問題GraphQL應運而生,其對應的能力爲:java
有了以上能力,前端就能夠根據已有的後端服務和實際業務要求靈活定製查詢請求,不用再去麻煩後端哥哥開發新的服務了。web
<!-- https://mvnrepository.com/artifact/com.graphql-java/graphql-spring-boot-starter -->
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>5.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.graphql-java/graphql-java-tools -->
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>5.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.graphql-java/graphiql-spring-boot-starter -->
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>5.0.2</version>
</dependency>
複製代碼
@Component
public class BookQueryResolver implements GraphQLQueryResolver {
public List<Book> findBooks() {
Author author = new Author(1, "Lee", 30);
Book book = new Book(1, "Java 8實戰", author, "電子工業出版社");
List<Book> bookList = new ArrayList<Book>();
bookList.add(book);
return bookList;
}
public Book findBook(Integer id) {
if (id == 1) {
Author author = new Author(1, "Lee", 30);
Book book = new Book(1, "Java 8實戰", author, "電子工業出版社");
return book;
} else {
return null;
}
}
public Dog findDog(String name) {
if (null != name && name.equals("xiaofei")) {
return new Dog("xiaofei", 3, "male");
} else {
return null;
}
}
}
複製代碼
能夠看到類上須要添加@Component註解。spring
type Author {
id: Int
name: String
age: Int
}
type Book {
id: Int
name: String
author: Author
publisher: String
}
type Dog {
name: String
age: Int
gender: String
}
複製代碼
type Query {
findBooks: [Book]
findBook(id:Int):Book findDog(name: String!):Dog findDogByName(name: String!):Dog } 複製代碼
以上完成以後就可使用查詢服務了。後端
GraphQL自帶了一個測試工具,瀏覽器中輸入: http://localhost:7000/graphiql 打開測試工具界面。(注:端口號爲spring端口號,請自行修改)。瀏覽器
完美實現了以前咱們提到的兩點要求。bash
在引入GraphQL以前,spring中前端和後端的接口經過Controller鏈接,若是Controller能被複用,不須要再從新寫QueryResolver那不是完美了,實踐證實,二者能夠共存,只要Controller類實現GraphQLQueryResolver接口則可,這樣既能夠支持之前的Rest接口查詢,又能夠支持GraphQL查詢。參考代碼以下:微信
@RestController
public class QueryController implements GraphQLQueryResolver {
@RequestMapping("/findDogByName")
public Dog findDogByName(@RequestBody String name) throws Exception {
if (null != name && name.equals("xiaofei")) {
return new Dog("xiaofei", 3, "male");
} else {
return null;
}
}
}
複製代碼
end.app
完整實例代碼掃碼加入微信公衆號並回復:webfullstack,獲取倉庫地址。spring-boot
站點: javashizhan.com/
微信公衆號: