Java – spring: create any number of beans using factory beans

I have a factory ish bean that creates many objects at startup. I hope these objects themselves are spring beans

If I'm creating a single object, I can instantiate it using factory methods, for example (from spring docs section 4.3.2.3):

<!-- the factory bean,which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
  <!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->
<bean id="clientService"
      factory-bean="serviceLocator"
      factory-method="createClientServiceInstance"/>

If I know in advance that I have n objects, I can call n different methods, but I don't – my factory creates an unknown arbitrary number of objects

Who knows how to do this?

Their goal is to make them produce "appropriate" spring beans like the above; Specifically, they should be qualified as sources and targets for automatic assembly Note that this means that I don't just want to return a collection and treat it as a bean

I'm using spring 3.1.0 configured with XML

Solution

It seems that you need dynamic bean creation

Never tried, but as described in this question, you can try using beandefinitionbuilder It seems to have everything you need Use it from a factory bean (you don't need to define it as a factory bean now)

Editor: I found a good usage example here

It's like:

String className = ... // get class name from wherever you get it

// Build your dynamic bean:
BeanDeFinitionBuilder bdb = BeanDeFinitionBuilder.genericBeanDeFinition(className);
bdb.setSingleton(true);
// add dependencies:
bdb.addDependsOn(dependeeBeanName);
// Eventually - validate it and get it:
AbstractBeanDeFinitionb bean = db.getBeanDeFinition();

// I guess only Now you get other already existing beans
// and make them depend on the one you created in the same way
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>