【问题标题】:Spring FactoryBean method with arguments带参数的 Spring FactoryBean 方法
【发布时间】:2014-03-26 16:21:17
【问题描述】:

我正在通过 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("bean", 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: No qualifying bean of type [...model.Picture] found for dependency.

【问题讨论】:

  • PictureBeanPicture是什么关系? FactoryBean 是什么类?
  • Picture 是一个持久性实体,PictureBean(可能名称有点混乱)应该是 Picture 的包装器,提供额外的方法。
  • 我可能混淆了 FactoryBean 和工厂方法。为了练习,我现在实现了 FactoryBean。但同样的问题又来了:如何以编程方式将参数传递给 FactoryBean? getBean(bean, args) 会将它们传递到哪里?

标签: java spring configuration annotations


【解决方案1】:

使用像这样的 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。

【讨论】:

  • 非常感谢。我的错误是工厂方法的名称。我把它改成了pictureBean,现在一切正常。
猜你喜欢
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 2013-12-23
相关资源
最近更新 更多