如何以编程方式在Spring中注册FactoryBean的实例 [英] How to programatically register an instance of a FactoryBean in Spring
问题描述
我有一组 FactoryBean
的实例,其类型为 MyFactoryBean
。构造函数接受 Class<?>
并使用它来确定从 getObject()
返回的内容:
I have a set of instances of FactoryBean
which are of type MyFactoryBean
. The constructor takes a Class<?>
and uses that to determine what to return from 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
的构造函数的类型实例是从上下文中请求的。
My end result is to control what is returned when an instance of type passed to the constructor of the MyFactoryBean
is requested from the context.
我可以用my注册它们像这样的上下文:
I can register them with my context like this:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getBeanFactory().registerSingleton(..., ...);
但感觉不对,自动装配不起作用。如何在我的上下文中注册这些?
But it doesn't feel right, and autowiring doesn't work. How do I register these with my context?
编辑:自动装配,我有Sean Patrick Floyd在这里回应:如何获得由FactoryBean spring创建的bean管理?但这仍然无法回答我的问题。
for the autowiring, I have noted Sean Patrick Floyd response here: How to get beans created by FactoryBean spring managed? but this still doesn't answer my question.
推荐答案
我创建了这个解决方案最后,但我不确定它是否是最好的:
I created this solution in the end, but I am not sure whether its the best or not:
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 { }
});
这篇关于如何以编程方式在Spring中注册FactoryBean的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!