mar*_*man 4 java configuration spring annotations
我正在通过XML配置和实例工厂方法实例化一些bean:
<bean id="galleryBeanFactory" class="de.tikron.webapp.gallery.bean.XmlGalleryBeanFactory" />
<bean id="pictureBean" factory-bean="galleryBeanFactory" factory-method="createPictureBean" scope="prototype" />
Run Code Online (Sandbox Code Playgroud)
我通过BeanFactory.getBean("bean",arguments ...)实例化我的原型bean编程:
BeanFactory bf = ContextLoader.getCurrentWebApplicationContext();
PictureBean pictureBean = (PictureBean) bf.getBean("pictureBean", picture);
Run Code Online (Sandbox Code Playgroud)
在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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题:我如何在这里传递参数?上面的代码导致org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到[... model.Picture]类型的限定bean.
用bean定义就好
@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
protected PictureBean createPictureBean(Picture picture) {
PictureBean bean = new PictureBean();
bean.setPicture(picture);
return bean;
}
Run Code Online (Sandbox Code Playgroud)
bean定义名称是createPictureBean.您可以通过每次调用它BeanFactory#getBean(String, Object...)像这样
ApplicationContext ctx = ...; // instantiate the AnnotationConfigApplicationContext
Picture picture = ...; // get a Picture instance
PictureBean pictureBean = (PictureBean) ctx.getBean("createPictureBean", picture);
Run Code Online (Sandbox Code Playgroud)
Spring将使用给定的参数(picture在本例中)来调用该@Bean方法.
如果你没有提供参数,Spring会在调用方法时尝试自动装配参数,但会因为Picture上下文中没有bean 而失败.
| 归档时间: |
|
| 查看次数: |
6272 次 |
| 最近记录: |