If someone ever needed to use @Primary on Spring Data repositories:
It looks like Spring Data JPA ignores @Primary
annotations on repositories.
As a workaround I have created BeanFactoryPostProcessor
which checks if given repository has @Primary
annotation and sets that bean as primary.
This is the code:
@Component
public class SpringDataPrimaryPostProcessor implements BeanFactoryPostProcessor {
public static final String REPOSITORY_INTERFACE_PROPERTY = "repositoryInterface";
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
makeRepositoriesPrimary(getRepositoryBeans(beanFactory));
}
protected List<BeanDefinition> getRepositoryBeans(ConfigurableListableBeanFactory beanFactory) {
List<BeanDefinition> springDataRepositoryDefinitions = Lists.newArrayList();
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
String beanClassName = beanDefinition.getBeanClassName();
try {
Class<?> beanClass = Class.forName(beanClassName);
if (isSpringDataJpaRepository(beanClass)) {
springDataRepositoryDefinitions.add(beanDefinition);
}
} catch (ClassNotFoundException e) {
throw new ApplicationContextException(String.format("Error when trying to create instance of %s", beanClassName), e);
}
}
return springDataRepositoryDefinitions;
}
protected void makeRepositoriesPrimary(List<BeanDefinition> repositoryBeans) {
for (BeanDefinition repositoryBeanDefinition : repositoryBeans) {
String repositoryInterface = (String) repositoryBeanDefinition.getPropertyValues().get(REPOSITORY_INTERFACE_PROPERTY);
if (isPrimary(repositoryInterface)) {
log.debug("Making site repository bean primary, class: {}", repositoryInterface);
repositoryBeanDefinition.setPrimary(true);
}
}
}
protected boolean isSpringDataJpaRepository(Class<?> beanClass) {
return RepositoryFactoryInformation.class.isAssignableFrom(beanClass);
}
private boolean isPrimary(String repositoryInterface) {
return AnnotationUtils.findAnnotation(getClassSafely(repositoryInterface), Primary.class) != null;
}
private Class<?> getClassSafely(String repositoryInterface) {
try {
return Class.forName(repositoryInterface);
} catch (ClassNotFoundException e) {
throw new ApplicationContextException(String.format("Error when trying to create instance of %s", repositoryInterface), e);
}
}