如何在Spring中以编程方式注册FactoryBean的实例

时间:2014-09-03 16:15:37

标签: java spring

我有一组FactoryBeanMyFactoryBean类型的实例。构造函数使用Class<?>并使用它来确定从getObject()返回的内容:

public class MyFactoryBean implements FactoryBean {

    private final Class<?> type;

    public MyFactoryBean(Class<?> type) {
        this.type = type;
    }

    @Override
    public Object getObject() throws Exception {
        return null; // Obviously I return something here rather than null!
    }

    @Override
    public Class<?> getObjectType() {
        return type;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

我的最终结果是控制从上下文请求传递给MyFactoryBean的构造函数的类型实例时返回的内容。

我可以用我的上下文注册它们:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getBeanFactory().registerSingleton(..., ...);

但它感觉不对,自动装配不起作用。如何在我的上下文中注册这些?


编辑:对于自动装配,我已经注意到Sean Patrick Floyd的回复:How to get beans created by FactoryBean spring managed?但是这仍然没有回答我的问题。

2 个答案:

答案 0 :(得分:2)

我最终创建了这个解决方案,但我不确定它是否是最好的:

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.addBeanFactoryPostProcessor(new BeanDefinitionRegistryPostProcessor() {

        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
            ConstructorArgumentValues cav = new ConstructorArgumentValues();
            cav.addGenericArgumentValue(MyClass.class);

            RootBeanDefinition bean = new RootBeanDefinition(MyFactoryBean.class, cav, null);
            AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();

            registry.registerBeanDefinition(generator.generateBeanName(bean, registry), bean);
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { }
    });

答案 1 :(得分:0)

查看以下讨论:How to inject dependencies into a self-instantiated object in Spring?

我相信这正是您所需要的:使用AutowireCapableBeanFactory