1

I am currently writing a Spring Boot autoconfiguration for Retrofit 2. What I am trying to do is to write some sort of an interface builder that is able instantiate an interface that is annotated with some annotation for autowiring just like Spring Data does it with repositories. As I cannot find any resources on how to do this (or if it can even be done with Spring), I would like to ask for your thoughts on that. Below is for an interface that I would like to instantiate.
My replacement for @Repository is @Retrofit the rest is just "ordinary" code you would write for any Retrofit repository.

The kind of interface I would like to autowire:

@Retrofit
public interface Api {

    @GET("usernames")
    String[] getUsernames();
}

An example for autowiring:

@SpringBootApplication
public class TestApplication {

    @Autowired
    private Api api;

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Bean
    CommandLineRunner runner() {
        return args -> {
            System.out.println(api.getUsernames());
        };
    }
}
2
  • Did you try to autowire it ? if so can you please place code and errors if exist.
    – MrMisery
    Aug 19, 2017 at 18:17
  • I have added an example, which obviously does not work, because no instance of the given interface can be found. Error is Field api in com.example.TestApplication required a bean of type 'com.example.Api' that could not be found. Aug 20, 2017 at 14:05

2 Answers 2

4

As I said I found a solution for my problem.

First we need an auto configuration class that is loaded by Spring Boot - as stated here - by adding the file META-INF/spring.factories with the content that is shown below. This auto configuration loads a registrar which itself searches for classes annotated with @Retrofit via a component provider. At last the registrar creates instances of RetrofitFactoryBean for each instance that could be found while this factory bean creates the Retrofit proxies itself.

The auto configuration

@Configuration
@Import(RetrofitRegistrar.class)
public class RetrofitAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public Retrofit retrofit() {
        return new Retrofit.Builder().build();
    }
}

META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
spring.retrofit.RetrofitAutoConfiguration

The imported registrar

public class RetrofitRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware {

    @Setter
    private BeanFactory beanFactory;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
            BeanDefinitionRegistry registry) {
        List<String> basePackages = AutoConfigurationPackages.get(this.beanFactory);
        RetrofitComponentProvider provider = new RetrofitComponentProvider(registry);
        basePackages.stream()
                .map(provider::findCandidateComponents)
                .flatMap(Set::stream)
                .forEach(comp -> register(comp, registry));
    }

    private void register(BeanDefinition component, BeanDefinitionRegistry registry) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.
                rootBeanDefinition(RetrofitFactoryBean.class);
        builder.addConstructorArgValue(component.getBeanClassName());
        registry.registerBeanDefinition(
                component.getBeanClassName().toLowerCase(), builder.getBeanDefinition());
    }
}

The component provider

class RetrofitComponentProvider extends ClassPathScanningCandidateComponentProvider {

    @Getter
    private BeanDefinitionRegistry registry;

    public RetrofitComponentProvider(BeanDefinitionRegistry registry) {
        super(false);

        Assert.notNull(registry, "BeanDefinitionRegistry must not be null!");
        this.registry = registry;

        addIncludeFilter(new AnnotationTypeFilter(Retrofit.class, true, true));
    }

    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return true;
    }
}

The factory bean

@Component
@RequiredArgsConstructor
public class RetrofitFactoryBean extends AbstractFactoryBean<Object> {

    @Getter
    private final Class<?> objectType;
    private final retrofit2.Retrofit retrofit;

    @Override
    protected Object createInstance() throws Exception {
        return retrofit.create(objectType);
    }
}

The @Getter, @Setter and @RequiredArgsConstructor annotations are provided by ProjectLombok

-1

Let me ask you firstly to avoid reinventing the wheel by creating a new Spring annotation (yours here is @Retrofit. However, it is absolutely okay to use retrofit with spring there is nothing to prevent it. You can simply try to use an existing Spring annotation which can be @Component as you can see in this question you can autowire your interface without facing problems.
Hope this helps.

1
  • In the question you linked an implementation for the interface is given by the user. I do not want the user to have to do that but rather want to have "the framework" do the work of instantiating the interfaces using Retrofit's instantiation mechanism. That's why I mentioned Spring Data which also instantiates interfaces all by itself. Aug 20, 2017 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.