Search code examples
javaspringspring-ioc

How to create a bean by type in Spring?


In my ApplicationContext I have several Beans being created the same style. So I have a lot of dublicated code writing a FactoryBean for each of this beans. Those beans have a common ground, implementing all one special interface.

I would like to move all that bean creation to one factory. That one would have to provide a methode like this

<T extends CommonInterface> T createInstance(Class<T> clazz);

There I could implement all the instantiation necessary to create one of my special beans.

My implementation would be called by spring for

@Autowired
private MyCommonInterfaceImplementation impl;

in that way

createInstance(MyCommonInterfaceImplementation.class)

So far I looked at BeanFactory and FactoryBean, both seem not to be I'm searching for.

Any suggestions?


Solution

  • why not use @bean

    @Bean
    public MyCommonInterfaceImplementation getMyCommonInterfaceImplementation(){
        return MyBeanFactory.createInstance(MyCommonInterfaceImplementation.class);
    }
    
    //should autowire here
    @Autowired
    private MyCommonInterfaceImplementation impl;