简体   繁体   中英

Spring: Creating an arbitrary number of beans using a factory bean

I have a factory-ish bean that creates a number of objects on startup, and I want these objects to themselves be Spring beans.

If I were creating a single object I could do instantiation with a factory method, eg. (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"/>

And if I knew ahead of time that I'd have n objects, I could call n different methods, but I don't - my factory creates an arbitrary number of objects not known ahead of time.

Does anyone know how to do this?

The goal is for them to be "proper" Spring beans like the above would produce; specifically, they should be eligible for autowiring both as sources and targets. Note this means I don't just want to return a Collection and have that be the bean.

I'm using XML-configured Spring 3.1.

Seems like you need dynamic bean creation...

Never tried it before but as mentioned in this question , you might try using BeanDefinitionBuilder . Seems it has all you need. Use it from your factory bean (which doesn't really need to be defined as factory bean now).

EDIT: I found a nice usage example here .

Something 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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM