graphql-java-annotations icon indicating copy to clipboard operation
graphql-java-annotations copied to clipboard

Invoke a callback when a DataFetcher is created

Open asinbow opened this issue 4 years ago • 2 comments

We are developing with Spring framework, which is famous for its @Autowired and @Bean. But when we are implementing a DataFetcher, we can not leverage this, because the DataFetcher will be created by Java reflection without a Spring ApplicationContext.

If there is a configuration callback in GraphQLAnnotations, we can autowire them manually.

AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
factory.autowireBean(dataFetcher);
factory.initializeBean(dataFetcher, "dataFetcher");

e.g. the callback can be invoked here: https://github.com/Enigmatis/graphql-java-annotations/blob/9ef5836e716d8039301e6561fe3bce7e0970b142/src/main/java/graphql/annotations/processor/retrievers/fieldBuilders/method/MethodDataFetcherBuilder.java#L72

Any better suggestion about it? If there is a good decision, I'd like to make the PR. Thanks!

asinbow avatar Mar 28 '20 04:03 asinbow

I have seen this kind of implementation:

public abstract class SpringDataFetcher<T> extends CustomDataFetcher<T> implements DataFetcher<T> {

    /**
     * Overrides the get method so it can be used with spring.
     *
     * @param environment
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public T get(DataFetchingEnvironment environment) {
        return getFetchedData(environment, (CustomDataFetcher<T>) applicationContext.getBean(this.getClass()));
    }
}

When CustomDataFetcher implements ApplicationContextAware, and has an abstract fetch method that should be overriden.

Well, I guess your solution might be cleaner. Tell me what you think. You are welcome to create this PR

yarinvak avatar May 02 '20 16:05 yarinvak

Sorry fo nearly forgetting this thread. In you sample code, how do you pass in the variable applicationContext?

asinbow avatar Jul 27 '20 00:07 asinbow

Hi @asinbow ,

We're helping with project maintenance and reviewing the list of opened PRs and Issues.

This issue was created quite a while ago, we were wondering if you were still interested in the outcome, please let us know if this is the case.

Without an answer by July 1st, 2023, this issue will be closed as "inactive" (and can always be re-opened later on if needed).

Thanks,

Fgerthoffert avatar Jun 02 '23 08:06 Fgerthoffert