2014-03-26 51 views
1

我通过实例化XML配置和实例工厂方法的一些豆类:的FactoryBean方法与参数

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

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

我实例化我的原型豆类方案由BeanFactory.getBean(“豆”,参数......):

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

随着春季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。

+0

'PictureBean'和'Picture'之间的关系是什么?什么类是'FactoryBean'? –

+0

图片是一个持久化实体,PictureBean(可能名字有点混乱)应该是提供附加方法的图片的包装。 – marsman

+0

我可能混淆了FactoryBean和工厂方法。对于练习,我已经实现了FactoryBean 。但是同样的问题再次出现:我如何通过编程方式将参数传递给FactoryBean? getBean(bean,args)在哪里通过? – marsman

回答

4

有了一个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。

+0

非常感谢。我的错误是工厂方法的名称。我将它改为pictureBean,现在一切正常。 – marsman