带有参数的Spring FactoryBean方法

时间:2014-03-26 16:21:17

标签: java spring configuration annotations

我通过XML配置和实例工厂方法实例化一些bean:

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

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

我通过BeanFactory.getBean(&#34; bean&#34;,arguments ...)实例化我的原型bean编程:

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

使用Spring 3,我想更改为带注释的基于java的bean配置。这是我的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;
  }
}

我的问题:我如何在这里传递参数?上面的代码导致org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到类型为[... model.Picture]的限定bean用于依赖。

1 个答案:

答案 0 :(得分:5)

使用像

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

bean定义名称为createPictureBean。您可以每次使用BeanFactory#getBean(String, Object...)来调用它

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

Spring将使用给定的参数(在本例中为picture)来调用@Bean方法。

如果你没有提供参数,Spring会在调用方法时尝试自动装配参数,但会因为上下文中没有Picture bean而失败。