如何在Spring中按类型创建bean? [英] How to create a bean by type in Spring?
问题描述
在我的ApplicationContext中,我创建了几个具有相同样式的Bean.因此,我有很多重复的代码为每个bean编写一个FactoryBean
.这些bean具有共同点,实现了所有一个特殊接口.
In my ApplicationContext I have several Beans being created the same style. So I have a lot of dublicated code writing a FactoryBean
for each of this beans. Those beans have a common ground, implementing all one special interface.
我想将所有的Bean创建转移到一个工厂.那将不得不提供这样的方法
I would like to move all that bean creation to one factory. That one would have to provide a methode like this
<T extends CommonInterface> T createInstance(Class<T> clazz);
我可以在其中实现创建我的一个特殊bean所需的所有实例化.
There I could implement all the instantiation necessary to create one of my special beans.
我的实现将在春季被调用
My implementation would be called by spring for
@Autowired
private MyCommonInterfaceImplementation impl;
以这种方式
createInstance(MyCommonInterfaceImplementation.class)
到目前为止,我查看的是BeanFactory
和FactoryBean
,两者似乎都不是我要搜索的.
So far I looked at BeanFactory
and FactoryBean
, both seem not to be I'm searching for.
有什么建议吗?
推荐答案
为什么不使用 查看全文