Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a respository populator bean using java config instead of XML?

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" />

How would the above be expressed in a java @Configuration class?

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

The above results in a FactoryBeanNotInitializedException with the message JacksonRepositoryPopulatorFactoryBean does not support circular references.

Any ideas?

like image 871
MrJohnBBQ Avatar asked Dec 16 '12 01:12

MrJohnBBQ


People also ask

How do I enable the repository interfaces in a Java based configuration file?

Enable Spring Data JPA by annotating the PersistenceContext class with the @EnableJpaRepositories annotation and also configure the base packages that are scanned when Spring Data JPA creates implementations for our repository interfaces.

What can be done to declare an instant repository with Spring data JPA?

Instant Repository is a term used in Spring Data. You create Instant Repository with these two steps 1. Annotate Domain class 2. Define your repository as an interface by extending Repository interface.


1 Answers

It's straight-forward actually:

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

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.

like image 155
Oliver Drotbohm Avatar answered Sep 30 '22 08:09

Oliver Drotbohm