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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With