我正在使用Spring&我的项目中的graphql-java(graphql-java-annotation).
为了检索数据部分,我使用DataFetcher从服务(从数据库)获取数据.
奇怪的是:myService始终为null.谁知道原因?
DataFetcher
@Component
public class MyDataFetcher implements DataFetcher {
// get data from database
@Autowired
private MyService myService;
@Override
public Object get(DataFetchingEnvironment environment) {
return myService.getData();
}
}
架构
@Component
@GraphQLName("Query")
public class MyGraphSchema {
@GraphQLField
@GraphQLDataFetcher(MyDataFetcher.class)
public Data getData() {
return null;
}
}
为MyService
@Service
public class MyService {
@Autowired
private MyRepository myRepo;
@Transactional(readOnly = true)
public Data getData() {
return myRepo.getData();
}
}
主要测试
@Bean
public String testGraphql(){
GraphQLObjectType object = GraphQLAnnotations.object(MyGraphSchema.class);
GraphQLSchema schema = newSchema().query(object).build();
GraphQL graphql = new GraphQL(schema);
ExecutionResult result = graphql.execute("{getData {id name desc}}");;
Map<String, Object> v = (Map<String, Object>) result.getData();
System.out.println(v);
return v.toString();
}
最佳答案:
由于在graphql-java-annotation中数据获取器是由注释定义的,它是由框架构造的(使用反射来获取构造函数),因此它不能是bean.
我发现的解决方法是将其设置为ApplicationContextAware,然后我可以初始化一些静态字段而不是bean.不是最好的东西,但它有效:
@Component
public class MyDataFetcher implements DataFetcher, ApplicationContextAware {
private static MyService myService;
private static ApplicationContext context;
@Override
public Object get(DataFetchingEnvironment environment) {
return myService.getData();
}
@override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansExcepion {
context = applicationContext;
myService = context.getBean(MyService.class);
}
}
基本上你仍然会得到一个由graphQL初始化的数据提取器的新实例,但是spring会初始化它,并且由于myService是静态的,你将得到初始化的.