Parametrize Bean factory by type in spring boot

2019-07-23 18:00发布

问题:

I have a couple of interfaces which define some services:

public interface Service {
    // marker
}

public interface ServiceA extends Service {
    public method doA(AParameter a);
}

public interface ServiceB extends Service {
    public method doB(BParameter b, AnotherParameter c);
}

Their implementations are always built the same way:

@Bean
public ServiceA getService() {
    return new Servicebuilder().build(ServiceA.class);
}

@Bean
public ServiceB getService() {
    return new Servicebuilder().build(ServiceB.class);
}

I use them with standard autowiring

class Controller {

     private final ServiceA serviceA;

     private final ServiceB serviceB;

     @Autowired
     public Controller(ServiceA service A, ServiceB serviceB) {
         this.serviceA = serviceA;
         this.serviceB = serviceB;
     }
}

Now I want my team to be able to add new services simple by defining the interface without having to write the bean provider each time. So in principle, I want to do something like

@Bean
public <T extends Service> T getService(Class<T> clazz) {
    return new Servicebuilder().build(clazz);
}

However, this fails with

Parameter 0 of constructor in Controller required a bean of type 'ServiceA' that could not be found.

I am using Spring Boot 1.5.1.

I have already looked at custom Qualifiers and there are lots of answers regarding generics in Beans. However none seems to fit my situation. Is there a way to achieve this?