marsman
marsman

Reputation: 53

Spring FactoryBean method with arguments

I'm instantiating some beans by XML configuration and instance factory methods:

<bean id="galleryBeanFactory" class="de.tikron.webapp.gallery.bean.XmlGalleryBeanFactory" />

<bean id="pictureBean" factory-bean="galleryBeanFactory" factory-method="createPictureBean" scope="prototype" />

I instantiate my prototype beans programmatic by BeanFactory.getBean("bean", arguments...):

BeanFactory bf = ContextLoader.getCurrentWebApplicationContext();
PictureBean pictureBean = (PictureBean) bf.getBean("pictureBean", picture);

With Spring 3 I want to change to annotated java-based bean configuration. Here is my FactoryBean:

@Configuration
public class AnnotatedGalleryBeanFactory implements GalleryBeanFactory

  @Bean
  @Scope(BeanDefinition.SCOPE_PROTOTYPE)
  protected PictureBean createPictureBean(Picture picture) {
    PictureBean bean = new PictureBean();
    bean.setPicture(picture);
    return bean;
  }
}

My Question: How can I pass parameters here? The code above results into org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [...model.Picture] found for dependency.

Upvotes: 5

Views: 10877

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279930

With a bean definition like

@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
protected PictureBean createPictureBean(Picture picture) {
    PictureBean bean = new PictureBean();
    bean.setPicture(picture);
    return bean;
}

the bean definition name is createPictureBean. You can invoke it every time using BeanFactory#getBean(String, Object...) like so

ApplicationContext ctx = ...; // instantiate the AnnotationConfigApplicationContext 
Picture picture = ...; // get a Picture instance
PictureBean pictureBean = (PictureBean) ctx.getBean("createPictureBean", picture);

Spring will use the arguments given (picture in this case) to invoke the @Bean method.

If you weren't providing arguments, Spring would try to autowire arguments when invoking the method but would fail because there was no Picture bean in the context.

Upvotes: 13

Related Questions