【问题标题】:Spring getBean(Class<T> interfaceToCreate, Object... args) method is missing?缺少 Spring getBean(Class<T> interfaceToCreate, Object... args) 方法?
【发布时间】:2012-10-23 20:11:46
【问题描述】:

我试图为我的 spring bean 创建工厂类

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);
    }
}

方法AppContext.getApplicationContext()返回ApplicationContext对象

在这里我应该可以创建一个像这样的spring bean:

@Autowired
protected MyFactory factory;

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

BeanFactory 没有公开任何方法,例如:getBean(Class&lt;T&gt; clazz, Object... args) 而且我没有MyBeanImpl 类的默认构造函数

有谁知道如何做到这一点?

【问题讨论】:

    标签: spring


    【解决方案1】:

    您可以分两步实现。 ListableBeanFactory 提供了一个方法String[] getBeanNamesForType(Class&lt;?&gt; type)。获得类型的 bean 名称后,您可以调用 BeanFactory.getBean(String name, Object... args)

    【讨论】:

    • 这确实有效,我们可以靠它生存,但 spring 可以提供这个:getBean(Class&lt;T&gt; clazz, Object… args) 签名。感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多