DATAJPA-1394 - EntityPathResolver selection is now done via ObjectProvider.

Instead of manually triggering a beans-of-type lookup via BeanLookup, we now rather get an ObjectProvider for EntityPathResolver injected and rely on its ….getIfAvailable(…) semantics to fallback to the default or reject the lookup if multiple instances were registered.

Changed the test cases to integration ones as we now need to verify the container interaction.

Related ticket: DATAJPA-1234.
This commit is contained in:
Oliver Gierke
2018-08-09 14:36:41 +02:00
parent 99b946563a
commit de0a510c15
3 changed files with 124 additions and 120 deletions

View File

@@ -18,16 +18,14 @@ package org.springframework.data.jpa.repository.support;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.querydsl.EntityPathResolver;
import org.springframework.data.querydsl.SimpleEntityPathResolver;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport;
import org.springframework.data.util.BeanLookup;
import org.springframework.data.util.Lazy;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@@ -45,7 +43,7 @@ public class JpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID>
extends TransactionalRepositoryFactoryBeanSupport<T, S, ID> {
private @Nullable EntityManager entityManager;
private Lazy<EntityPathResolver> entityPathResolver = Lazy.of(SimpleEntityPathResolver.INSTANCE);
private EntityPathResolver entityPathResolver;
/**
* Creates a new {@link JpaRepositoryFactoryBean} for the given repository interface.
@@ -75,6 +73,17 @@ public class JpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID>
super.setMappingContext(mappingContext);
}
/**
* Configures the {@link EntityPathResolver} to be used. Will expect a canonical bean to be present but fallback to
* {@link SimpleEntityPathResolver#INSTANCE} in case none is available.
*
* @param resolver must not be {@literal null}.
*/
@Autowired
public void setEntityPathResolver(ObjectProvider<EntityPathResolver> resolver) {
this.entityPathResolver = resolver.getIfAvailable(() -> SimpleEntityPathResolver.INSTANCE);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport#doCreateRepositoryFactory()
@@ -92,10 +101,8 @@ public class JpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID>
*/
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
EntityPathResolver resolver = entityPathResolver.get();
JpaRepositoryFactory jpaRepositoryFactory = new JpaRepositoryFactory(entityManager);
jpaRepositoryFactory.setEntityPathResolver(resolver);
jpaRepositoryFactory.setEntityPathResolver(entityPathResolver);
return jpaRepositoryFactory;
}
@@ -111,18 +118,4 @@ public class JpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID>
super.afterPropertiesSet();
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport#setBeanFactory(org.springframework.beans.factory.BeanFactory)
*/
public void setBeanFactory(BeanFactory beanFactory) {
Assert.isInstanceOf(ListableBeanFactory.class, beanFactory);
super.setBeanFactory(beanFactory);
this.entityPathResolver = BeanLookup.lazyIfAvailable(EntityPathResolver.class, beanFactory) //
.or(SimpleEntityPathResolver.INSTANCE);
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright 2017-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jpa.repository.support;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.jpa.repository.sample.UserRepository;
import org.springframework.data.querydsl.EntityPathResolver;
import org.springframework.data.querydsl.SimpleEntityPathResolver;
import org.springframework.test.util.ReflectionTestUtils;
import com.querydsl.core.types.EntityPath;
/**
* Unit tests for {@link EntityPathResolver} related tests on {@link JpaRepositoryFactoryBean}.
*
* @author Jens Schauder
* @author Oliver Gierke
*/
public class JpaRepositoryFactoryBeanEntityPathResolverIntegrationTests {
@Configuration
@ImportResource("classpath:infrastructure.xml")
@EnableJpaRepositories(basePackageClasses = UserRepository.class, //
includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = UserRepository.class))
static class BaseConfig {
static final EntityPathResolver RESOLVER = new EntityPathResolver() {
@Override
public <T> EntityPath<T> createPath(Class<T> domainClass) {
return null;
}
};
}
@Configuration
static class FirstEntityPathResolver {
@Bean
EntityPathResolver firstEntityPathResolver() {
return BaseConfig.RESOLVER;
}
}
@Configuration
static class SecondEntityPathResolver {
@Bean
EntityPathResolver secondEntityPathResolver() {
return BaseConfig.RESOLVER;
}
}
@Test // DATAJPA-1234, DATAJPA-1394
public void usesSimpleEntityPathResolverByDefault() {
assertEntityPathResolver(SimpleEntityPathResolver.INSTANCE, BaseConfig.class);
}
@Test // DATAJPA-1234, DATAJPA-1394
public void usesExplicitlyRegisteredEntityPathResolver() {
assertEntityPathResolver(BaseConfig.RESOLVER, BaseConfig.class, FirstEntityPathResolver.class);
}
@Test // DATAJPA-1234, DATAJPA-1394
public void rejectsMulitpleEntityPathResolvers() {
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BaseConfig.class,
FirstEntityPathResolver.class, SecondEntityPathResolver.class);
context.close();
}).withCauseExactlyInstanceOf(NoUniqueBeanDefinitionException.class);
}
private static void assertEntityPathResolver(EntityPathResolver resolver, Class<?>... configurations) {
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configurations)) {
JpaRepositoryFactoryBean<?, ?, ?> factory = context.getBean("&userRepository", JpaRepositoryFactoryBean.class);
assertThat(ReflectionTestUtils.getField(factory, "entityPathResolver")).isEqualTo(resolver);
}
}
}

View File

@@ -1,98 +0,0 @@
/*
* Copyright 2017-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jpa.repository.support;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.data.querydsl.EntityPathResolver;
import org.springframework.data.querydsl.SimpleEntityPathResolver;
import org.springframework.data.repository.Repository;
import org.springframework.data.util.Lazy;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit tests for {@link EntityPathResolver} related tests on {@link JpaRepositoryFactoryBean}.
*
* @author Jens Schauder
* @author Oliver Gierke
*/
public class JpaRepositoryFactoryBeanEntityPathResolverUnitTests {
ListableBeanFactory beanFactory = mock(ListableBeanFactory.class);
JpaRepositoryFactoryBean<DummyRepository, DummyEntity, Long> factoryBean = new JpaRepositoryFactoryBean<>(
DummyRepository.class);
Map<String, EntityPathResolver> beans = new HashMap<>();
SimpleEntityPathResolver pathResolver = new SimpleEntityPathResolver("aSuffix");
@Before
public void setup() {
doReturn(beans).when(beanFactory).getBeansOfType(EntityPathResolver.class, false, false);
}
@Test // DATAJPA-1234
public void withoutConfiguredBeanTheDefaultInstanceIsUsed() throws Exception {
factoryBean.setBeanFactory(beanFactory);
assertThat(extractEntityPathResolver(factoryBean).get()).isEqualTo(SimpleEntityPathResolver.INSTANCE);
}
@Test // DATAJPA-1234
public void aSingleBeanOfTypeEntityPathResolverIsUsed() throws Exception {
beans.put("irrelevant", pathResolver);
factoryBean.setBeanFactory(beanFactory);
assertThat(extractEntityPathResolver(factoryBean).get()).isEqualTo(pathResolver);
}
@Test // DATAJPA-1234
public void withMultipleEntityPathResolversAnExceptionIsThrown() throws Exception {
beans.put("irrelevant", pathResolver);
beans.put("other", new SimpleEntityPathResolver("anotherSuffix"));
factoryBean.setBeanFactory(beanFactory);
factoryBean.setEntityManager(mock(EntityManager.class));
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class) //
.isThrownBy(() -> factoryBean.afterPropertiesSet());
}
@SuppressWarnings("unchecked")
private Lazy<EntityPathResolver> extractEntityPathResolver(
JpaRepositoryFactoryBean<DummyRepository, DummyEntity, Long> factoryBean) {
return (Lazy<EntityPathResolver>) ReflectionTestUtils.getField(factoryBean, "entityPathResolver");
}
static class DummyEntity {}
interface DummyRepository extends Repository<DummyEntity, Long> {}
}