如何在Spring中引用依赖关系实现时动态创建它们?

如何在Spring中引用依赖关系实现时动态创建它们?,spring,Spring,这里的情况是,我有一个具有动态实现的接口。这些实现需要在运行时实例化,并通过注入接口使用: public interface Configuration { void doStuff(); } public interface ExampleConfiguration extends Configuration { void doStuff(); } ExampleConfiguration具有动态生成的实现。也就是说,没有ExampleConfigurationMPL类。事

这里的情况是,我有一个具有动态实现的接口。这些实现需要在运行时实例化,并通过注入接口使用:

public interface Configuration {
    void doStuff();
}

public interface ExampleConfiguration extends Configuration {
    void doStuff();
}
ExampleConfiguration具有动态生成的实现。也就是说,没有ExampleConfigurationMPL类。事实证明,这很难集成到Spring中,因为我希望自动注入这些生成的实现:

@Autowired
private ExampleConfiguration config;
我一直在添加BeanPostProcessor,但看起来没有解决依赖关系(正如我预期的那样)

本质上,是否有一种方法可以贡献一个工厂(使用上下文信息,例如DependencyDescriptor实例)来调用该工厂,以尝试解决缺少的依赖关系?将有多个接口扩展配置接口

Spring版本是3.0.3。

您试过一个吗


Spring将在被请求时调用
getObject()

我想您已经找到了实际制作实例的方法了?好的,您所需要做的就是将工厂本身变成一个bean,并添加正确的注释:

@org.springframework.context.annotation.Configuration
public class ConfigBean {
    @org.springframework.context.annotation.Bean
    public ExampleConfiguration getObject() throws Exception {
        return //...magic here
    }
}

您可以使用常用的Spring技术来连接到所需的任何配置。(我假设您使用的是
…)

+1/2-您能否显示
applicationContext.XML
中所需的XML来设置和引用factory bean?因此,我采用了factory bean方法,但问题是存在多种扩展配置的接口情况。对于配置的每个扩展,我都需要一个工厂bean。这种方法的唯一问题是,我需要为基本接口的每个实现创建一个新方法。
<bean id="exampleConfigurationFactoryBean" class="ExampleConfigurationFactoryBean"/>
<bean id="someBean">
    <!-- exampleConfiguration is of ExampleConfiguration type -->
    <property name="exampleConfiguration" ref="exampleConfigurationFactoryBean"/>
</bean>
@org.springframework.context.annotation.Configuration
public class ConfigBean {
    @org.springframework.context.annotation.Bean
    public ExampleConfiguration getObject() throws Exception {
        return //...magic here
    }
}