mibutec mibutec - 1 year ago 49
Java Question

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

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

private MyCommonInterfaceImplementation impl;

in that way


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

Any suggestions?

Answer Source

why not use @bean

public MyCommonInterfaceImplementation getMyCommonInterfaceImplementation(){
    return MyBeanFactory.createInstance(MyCommonInterfaceImplementation.class);

//should autowire here
private MyCommonInterfaceImplementation impl;