Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring getBean(Class<T> interfaceToCreate, Object... args) method is missing?

Tags:

spring

I was trying to create factory class for my spring beans

public interface MyBean implements TBean{}

@Component
@Scope("prototype")
public class MyBeanImpl implements MyBean{
   public MyBeanImpl(Request request){//..}
}

@Component
public class MyFactory {
    public <T extends TBean> T createbean(Class<T> interfaceToCreate, Object... args) {
        return (T)AppContext.getApplicationContext().getBean(interfaceToCreate, args);
    }
}

method AppContext.getApplicationContext() returns ApplicationContext object

here I should be be able to create a spring bean like:

@Autowired
protected MyFactory factory;

Request myRequest;
void somemethod(){
    factory.createbean(MyBean.class, myRequest)
}

but BeanFactory does not expose any method like: getBean(Class<T> clazz, Object... args) And I do not have default constructor for MyBeanImpl class

Does anyone know how to accomplish that?

like image 869
Elbek Avatar asked Sep 04 '26 08:09

Elbek


1 Answers

You can achieve that in two steps. The ListableBeanFactory provides a method String[] getBeanNamesForType(Class<?> type). Once you got the bean names for your type, you can invoke the BeanFactory.getBean(String name, Object... args).

like image 104
Costi Ciudatu Avatar answered Sep 07 '26 02:09

Costi Ciudatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!