Skip to content

DATAJDBC-330 - DI logic now runs after Spring Boot. #115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-relational-parent</artifactId>
<version>1.1.0.BUILD-SNAPSHOT</version>
<version>1.1.0.DATAJDBC-293-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data Relational Parent</name>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-jdbc-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-relational-parent</artifactId>
<version>1.1.0.BUILD-SNAPSHOT</version>
<version>1.1.0.DATAJDBC-293-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
4 changes: 2 additions & 2 deletions spring-data-jdbc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>spring-data-jdbc</artifactId>
<version>1.1.0.BUILD-SNAPSHOT</version>
<version>1.1.0.DATAJDBC-293-SNAPSHOT</version>

<name>Spring Data JDBC</name>
<description>Spring Data module for JDBC repositories.</description>
Expand All @@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-relational-parent</artifactId>
<version>1.1.0.BUILD-SNAPSHOT</version>
<version>1.1.0.DATAJDBC-293-SNAPSHOT</version>
</parent>

<properties>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,14 @@
*/
package org.springframework.data.jdbc.repository.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Supplier;

import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.data.jdbc.core.DataAccessStrategy;
import org.springframework.data.jdbc.repository.support.JdbcRepositoryFactoryBean;
import org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport;
import org.springframework.data.repository.config.RepositoryConfigurationSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
Expand Down Expand Up @@ -87,103 +74,20 @@ public void registerBeansForRoot(BeanDefinitionRegistry registry, RepositoryConf
}
}

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.data.repository.config.RepositoryConfigurationSource)
*/
@Override
public void postProcess(BeanDefinitionBuilder builder, RepositoryConfigurationSource source) {

resolveReference(builder, source, "jdbcOperationsRef", "jdbcOperations", NamedParameterJdbcOperations.class, true);
resolveReference(builder, source, "dataAccessStrategyRef", "dataAccessStrategy", DataAccessStrategy.class, false);
}

private void resolveReference(BeanDefinitionBuilder builder, RepositoryConfigurationSource source,
String attributeName, String propertyName, Class<?> classRef, boolean required) {

Optional<String> beanNameRef = source.getAttribute(attributeName).filter(StringUtils::hasText);

String beanName = beanNameRef.orElseGet(() -> determineMatchingBeanName(propertyName, classRef, required));

if (beanName != null) {
builder.addPropertyReference(propertyName, beanName);
} else {
Assert.isTrue(!required,
"The beanName must not be null when requested as 'required'. Please report this as a bug.");
}

}

@Nullable
private String determineMatchingBeanName(String propertyName, Class<?> classRef, boolean required) {
source.getAttribute("jdbcOperationsRef") //
.filter(s -> !StringUtils.isEmpty(s)) //
.ifPresent(s -> builder.addPropertyReference("jdbcOperations", s));

if (this.beanFactory == null) {
return nullOrThrowException(required,
() -> new NoSuchBeanDefinitionException(classRef, "No BeanFactory available."));
}

List<String> beanNames = Arrays.asList(beanFactory.getBeanNamesForType(classRef));

if (beanNames.isEmpty()) {
return nullOrThrowException(required,
() -> new NoSuchBeanDefinitionException(classRef, String.format("No bean of type %s available", classRef)));
}

if (beanNames.size() == 1) {
return beanNames.get(0);
}

if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {

return nullOrThrowException(required,
() -> new NoSuchBeanDefinitionException(String.format(
"BeanFactory does not implement ConfigurableListableBeanFactory when trying to find bean of type %s.",
classRef)));
}

List<String> primaryBeanNames = getPrimaryBeanDefinitions(beanNames, (ConfigurableListableBeanFactory) beanFactory);

if (primaryBeanNames.size() == 1) {
return primaryBeanNames.get(0);
}

if (primaryBeanNames.size() > 1) {
throw new NoUniqueBeanDefinitionException(classRef, primaryBeanNames.size(),
"more than one 'primary' bean found among candidates: " + primaryBeanNames);
}

for (String beanName : beanNames) {

if (propertyName.equals(beanName)
|| ObjectUtils.containsElement(beanFactory.getAliases(beanName), propertyName)) {
return beanName;
}
}

return nullOrThrowException(required,
() -> new NoSuchBeanDefinitionException(String.format("No bean of name %s found.", propertyName)));
}

private static List<String> getPrimaryBeanDefinitions(List<String> beanNames,
ConfigurableListableBeanFactory beanFactory) {

ArrayList<String> primaryBeanNames = new ArrayList<>();
for (String name : beanNames) {

if (beanFactory.getBeanDefinition(name).isPrimary()) {
primaryBeanNames.add(name);
}
}
return primaryBeanNames;
}

@Nullable
private static String nullOrThrowException(boolean required, Supplier<RuntimeException> exception) {

if (required) {
throw exception.get();
}
return null;
source.getAttribute("dataAccessStrategyRef") //
.filter(s -> !StringUtils.isEmpty(s)) //
.ifPresent(s -> builder.addPropertyReference("dataAccessStrategy", s));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import java.io.Serializable;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
Expand Down Expand Up @@ -47,6 +48,7 @@ public class JdbcRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extend
extends TransactionalRepositoryFactoryBeanSupport<T, S, ID> implements ApplicationEventPublisherAware {

private ApplicationEventPublisher publisher;
private BeanFactory beanFactory;
private RelationalMappingContext mappingContext;
private RelationalConverter converter;
private DataAccessStrategy dataAccessStrategy;
Expand Down Expand Up @@ -113,7 +115,6 @@ public void setQueryMappingConfiguration(QueryMappingConfiguration queryMappingC
/**
* @param rowMapperMap can be {@literal null}. {@link #afterPropertiesSet()} defaults to {@link RowMapperMap#EMPTY} if
* {@literal null}.
*
* @deprecated use {@link #setQueryMappingConfiguration(QueryMappingConfiguration)} instead.
*/
@Deprecated
Expand All @@ -131,6 +132,14 @@ public void setConverter(RelationalConverter converter) {
this.converter = converter;
}

@Override
public void setBeanFactory(BeanFactory beanFactory) {

super.setBeanFactory(beanFactory);

this.beanFactory = beanFactory;
}

/*
* (non-Javadoc)
* @see org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport#afterPropertiesSet()
Expand All @@ -141,17 +150,36 @@ public void afterPropertiesSet() {
Assert.state(this.mappingContext != null, "MappingContext is required and must not be null!");
Assert.state(this.converter != null, "RelationalConverter is required and must not be null!");

if (dataAccessStrategy == null) {

SqlGeneratorSource sqlGeneratorSource = new SqlGeneratorSource(mappingContext);
this.dataAccessStrategy = new DefaultDataAccessStrategy(sqlGeneratorSource, mappingContext, converter,
operations);
}
ensureJdbcOperationsIsInitialized();
ensureDataAccessStrategyIsInitialized();

if (queryMappingConfiguration == null) {
this.queryMappingConfiguration = QueryMappingConfiguration.EMPTY;
}

super.afterPropertiesSet();
}

private void ensureJdbcOperationsIsInitialized() {

if (operations != null) {
return;
}

operations = beanFactory.getBean(NamedParameterJdbcOperations.class);
}

private void ensureDataAccessStrategyIsInitialized() {

if (dataAccessStrategy != null) {
return;
}

dataAccessStrategy = beanFactory.getBeanProvider(DataAccessStrategy.class).getIfAvailable(() -> {

SqlGeneratorSource sqlGeneratorSource = new SqlGeneratorSource(mappingContext);
return new DefaultDataAccessStrategy(sqlGeneratorSource, mappingContext, converter, operations);
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.data.jdbc.testing.TestConfiguration;
Expand Down Expand Up @@ -105,6 +106,7 @@ SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory factory) {
}

@Bean
@Primary
MyBatisDataAccessStrategy dataAccessStrategy(SqlSession sqlSession) {

MyBatisDataAccessStrategy strategy = new MyBatisDataAccessStrategy(sqlSession);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jdbc.core.DataAccessStrategy;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.data.jdbc.testing.TestConfiguration;
Expand Down Expand Up @@ -88,8 +89,10 @@ SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory factory) {
}

@Bean
@Primary
DataAccessStrategy dataAccessStrategy(RelationalMappingContext context, RelationalConverter converter,
SqlSession sqlSession, EmbeddedDatabase db) {

return MyBatisDataAccessStrategy.createCombinedAccessStrategy(context, converter,
new NamedParameterJdbcTemplate(db), sqlSession);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public class EnableJdbcRepositoriesIntegrationTests {

@BeforeClass
public static void setup() {

MAPPER_MAP.setAccessible(true);
OPERATIONS.setAccessible(true);
DATA_ACCESS_STRATEGY.setAccessible(true);
Expand All @@ -105,8 +106,9 @@ public void customRowMapperConfigurationGetsPickedUp() {

@Test // DATAJDBC-293
public void jdbcOperationsRef() {

NamedParameterJdbcOperations operations = (NamedParameterJdbcOperations) ReflectionUtils.getField(OPERATIONS, factoryBean);
assertThat(operations).isNotSameAs(defaultDataAccessStrategy).isSameAs(qualifierJdbcOperations);
assertThat(operations).isNotSameAs(defaultOperations).isSameAs(qualifierJdbcOperations);

DataAccessStrategy dataAccessStrategy = (DataAccessStrategy) ReflectionUtils.getField(DATA_ACCESS_STRATEGY, factoryBean);
assertThat(dataAccessStrategy).isNotSameAs(defaultDataAccessStrategy).isSameAs(qualifierDataAccessStrategy);
Expand Down
Loading