如何使用java配置而不是XML来声明存储库填充器bean?

2022-09-03 05:58:39

我正在开发一个基于Spring的项目,该项目(到目前为止)完全没有XML,除了现在我已经用Spring JPA存储库填充器碰壁了:

<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();
}

上述结果导致带有消息 。FactoryBeanNotInitializedExceptionJacksonRepositoryPopulatorFactoryBean does not support circular references

有什么想法吗?


答案 1

它实际上很简单:

@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;
  }
}

通过返回自身,Spring 将负责调用所有必需的回调接口(即 等)。工厂 bean 是一个,因此在 完全初始化时将侦听并触发填充。FactoryBeansetApplicationContext(…)setBeanClassLoader(…)ApplicationListenerContextRefreshedEventApplicationContext


答案 2

推荐