Spring 提供了FactoryBean
允许对 bean 进行非平凡初始化的接口。该框架提供了许多工厂 bean 的实现,并且——当使用 Spring 的 XML 配置时——工厂 bean 很容易使用。
但是,在 Spring 3.0 中,我找不到令人满意的方法来使用带有基于注释的配置(née JavaConfig)的工厂 bean。
显然,我可以手动实例化工厂 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 的更好解决方案?