如何使用Java config而不是XML声明存储库填充器bean? [英] How to declare a respository populator bean using java config instead of XML?
问题描述
我正在(到目前为止)完全不使用XML的基于Spring的项目,除非现在我已经用Spring JPA存储库填充器碰到了墙:
I am working on a Spring based project that is (so-far) completely XML-free, except now I've hit a wall with the Spring JPA repository populator:
<repository:jackson-populator location="classpath:data.json" />
以上如何在java @Configuration类中表达?
How would the above be expressed in a java @Configuration class?
这篇文章建议直接使用FactoryBean: https://stackoverflow.com/a/13566712/1746274
This post suggests using the FactoryBean directly: https://stackoverflow.com/a/13566712/1746274
我尝试过,得到的最接近的是以下内容,但这并不完全正确.
I tried that and the closest I got was the following but it's not quite right.
@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
.
The above results in a FactoryBeanNotInitializedException
with the message JacksonRepositoryPopulatorFactoryBean does not support circular references
.
有什么想法吗?
推荐答案
实际上很简单:
@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
,因此将在完全初始化ApplicationContext
时侦听ContextRefreshedEvent
并触发填充.
By returning the FactoryBean
itself, Spring will take care of invoking all the necessarry callback interfaces (i.e. setApplicationContext(…)
, setBeanClassLoader(…)
etc.). The factory bean is an ApplicationListener
and thus will listen to the ContextRefreshedEvent
and trigger population when the ApplicationContext
is fully initialized.
这篇关于如何使用Java config而不是XML声明存储库填充器bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!