我正在开发一个基于Spring的项目(迄今为止)完全没有XML,除了现在我已经使用Spring JPA存储库populator打了一堵墙:
<repository:jackson-populator location="classpath:data.json" />
如何在java @Configuration类中表达上述内容?
这篇文章建议直接使用FactoryBean: https://stackoverflow.com/a/13566712/1746274
我试过了,我得到的最接近的是以下但是不太正确。
@Bean(name="repositoryPopulator")
public RepositoryPopulator getRespositoryPopulator() throws Exception {
final JacksonRepositoryPopulatorFactoryBean factory = new JacksonRepositoryPopulatorFactoryBean();
factory.getObject().setResourceLocation("classpath:test-data.json");
factory.afterPropertiesSet();
return factory.getObject();
}
以上结果为FactoryBeanNotInitializedException
,邮件为JacksonRepositoryPopulatorFactoryBean does not support circular references
。
有什么想法吗?
答案 0 :(得分:23)
实际上是直截了当的:
@Configuration
class ApplicationConfig {
@Bean
public JacksonRepositoryPopulatorFactoryBean repositoryPopulator() {
Resource sourceData = new ClassPathResource("test-data.json");
JacksonRepositoryPopulatorFactoryBean factory = new JacksonRepositoryPopulatorFactoryBean();
// Set a custom ObjectMapper if Jackson customization is needed
factory.setObjectMapper(…);
factory.setResources(new Resource[] { sourceData });
return factory;
}
}
通过返回FactoryBean
本身,Spring将负责调用所有必需的回调接口(即setApplicationContext(…)
,setBeanClassLoader(…)
等)。工厂bean是ApplicationListener
,因此会在ContextRefreshedEvent
完全初始化时收听ApplicationContext
并触发填充。