※JAVA获取资源文件内容※

※使用ResourceUtils工具类(基于GraphQL查询):

 1 package cn.itcast.haoke.dubbo.api.graphql;
 2 
 3 import cn.itcast.haoke.dubbo.server.service.HouseResourcesService;
 4 import graphql.GraphQL;
 5 import graphql.schema.GraphQLSchema;
 6 import graphql.schema.idl.RuntimeWiring;
 7 import graphql.schema.idl.SchemaGenerator;
 8 import graphql.schema.idl.SchemaParser;
 9 import graphql.schema.idl.TypeDefinitionRegistry;
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.context.annotation.Bean;
12 import org.springframework.stereotype.Component;
13 import org.springframework.util.ResourceUtils;
14 
15 import javax.annotation.PostConstruct;
16 import java.io.File;
17 import java.io.IOException;
18 
19 @Component
20 public class GraphQLProvider {
21     private GraphQL graphQL;
22     @Autowired
23     private HouseResourcesService houseResourcesService;
24     @PostConstruct
25     public void init() throws IOException{
26         File file = ResourceUtils.getFile("classpath:haoke.graphqls");
27         GraphQLSchema graphQLSchema = buildSchema(file);
28         this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
29     }
30     private GraphQLSchema buildSchema(File file){
31         TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(file);
32         RuntimeWiring runtimeWiring = buildWiring();
33         SchemaGenerator schemaGenerator = new SchemaGenerator();
34         return schemaGenerator.makeExecutableSchema(typeRegistry,runtimeWiring);
35     }
36     private RuntimeWiring buildWiring(){
37         return RuntimeWiring.newRuntimeWiring().type("HaokeQuery",builder->builder.dataFetcher("HouseResources"
38                 ,enviroment->{
39             Long id = enviroment.getArgument("id");
40             return this.houseResourcesService.queryHouseResourcesById(id);
41                 })).build();
42     }
43     @Bean
44     public GraphQL graphQL(){
45         return graphQL;
46     }
47 }

※使用类加载器,并利用工具包转为字符串:

import org.apache.commons.io.IOUtils;

/*读取文件内容*/
    public static String readFileToString(String fileName){
        try {
            return IOUtils.toString(GraphQLSchema.class.getClassLoader().getResourceAsStream(fileName),"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

猜你喜欢

转载自www.cnblogs.com/zhuo-zui/p/12199611.html