【发布时间】:2011-07-29 07:19:47
【问题描述】:
Spring 提供了FactoryBean 接口以允许对bean 进行非平凡的初始化。该框架提供了许多工厂 bean 的实现,并且——当使用 Spring 的 XML 配置时——工厂 bean 很容易使用。
但是,在 Spring 3.0 中,我找不到一种令人满意的方式来使用工厂 bean 和基于注释的配置(née JavaConfig)。
显然,我可以手动实例化工厂 bean 并自己设置任何所需的属性,如下所示:
@Configuration
public class AppConfig {
...
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource());
factory.setAnotherProperty(anotherProperty());
return factory.getObject();
}
但是,如果 FactoryBean 实现了任何 Spring 特定的回调接口,例如 InitializingBean、ApplicationContextAware、BeanClassLoaderAware 或 @PostConstruct,这将失败。我还需要检查FactoryBean,找出它实现了哪些回调接口,然后通过调用setApplicationContext、afterPropertiesSet()等自己实现这个功能。
这让我感觉很尴尬和背对前:应用程序开发人员不应该实现 IOC 容器的回调。
有谁知道从 Spring Annotation 配置中使用 FactoryBeans 的更好解决方案?
【问题讨论】:
标签: java spring inversion-of-control spring-annotations