Parametrize Bean factory by type in spring boot

元气小坏坏 提交于 2020-01-05 07:19:07

问题


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?

来源:https://stackoverflow.com/questions/45188724/parametrize-bean-factory-by-type-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!