forked from spring-projects/spring-data-commons
/
RepositoryConfigurationDelegate.java
269 lines (242 loc) · 12.1 KB
/
RepositoryConfigurationDelegate.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
* Copyright 2014-2020 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
*
* https://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.repository.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.AutowireCandidateResolver;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.core.env.Environment;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.core.log.LogMessage;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StopWatch;
/**
* Delegate for configuration integration to reuse the general way of detecting
* repositories. Customization is done by providing a configuration format specific
* {@link RepositoryConfigurationSource} (currently either XML or annotations are
* supported). The actual registration can then be triggered for different
* {@link RepositoryConfigurationExtension} s.
*
* @author Oliver Gierke
* @author Jens Schauder
* @author Mark Paluch
*/
public class RepositoryConfigurationDelegate {
private static final String REPOSITORY_REGISTRATION = "Spring Data %s - Registering repository: %s - Interface: %s - Factory: %s";
private static final String MULTIPLE_MODULES = "Multiple Spring Data modules found, entering strict repository configuration mode!";
private static final String NON_DEFAULT_AUTOWIRE_CANDIDATE_RESOLVER = "Non-default AutowireCandidateResolver (%s) detected. Skipping the registration of LazyRepositoryInjectionPointResolver. Lazy repository injection will not be working!";
static final String FACTORY_BEAN_OBJECT_TYPE = "factoryBeanObjectType";
private static final Log logger = LogFactory.getLog(RepositoryConfigurationDelegate.class);
private final RepositoryConfigurationSource configurationSource;
private final ResourceLoader resourceLoader;
private final Environment environment;
private final boolean isXml;
private final boolean inMultiStoreMode;
/**
* Creates a new {@link RepositoryConfigurationDelegate} for the given
* {@link RepositoryConfigurationSource} and {@link ResourceLoader} and
* {@link Environment}.
* @param configurationSource must not be {@literal null}.
* @param resourceLoader must not be {@literal null}.
* @param environment must not be {@literal null}.
*/
public RepositoryConfigurationDelegate(RepositoryConfigurationSource configurationSource,
ResourceLoader resourceLoader, Environment environment) {
this.isXml = configurationSource instanceof XmlRepositoryConfigurationSource;
boolean isAnnotation = configurationSource instanceof AnnotationRepositoryConfigurationSource;
Assert.isTrue(this.isXml || isAnnotation,
"Configuration source must either be an Xml- or an AnnotationBasedConfigurationSource!");
Assert.notNull(resourceLoader, "ResourceLoader must not be null!");
this.configurationSource = configurationSource;
this.resourceLoader = resourceLoader;
this.environment = defaultEnvironment(environment, resourceLoader);
this.inMultiStoreMode = multipleStoresDetected();
}
/**
* Defaults the environment in case the given one is null. Used as fallback, in case
* the legacy constructor was invoked.
* @param environment can be {@literal null}.
* @param resourceLoader can be {@literal null}.
* @return
*/
private static Environment defaultEnvironment(@Nullable Environment environment,
@Nullable ResourceLoader resourceLoader) {
if (environment != null) {
return environment;
}
return resourceLoader instanceof EnvironmentCapable ? ((EnvironmentCapable) resourceLoader).getEnvironment()
: new StandardEnvironment();
}
/**
* Registers the found repositories in the given {@link BeanDefinitionRegistry}.
* @param registry
* @param extension
* @return {@link BeanComponentDefinition}s for all repository bean definitions found.
*/
public List<BeanComponentDefinition> registerRepositoriesIn(BeanDefinitionRegistry registry,
RepositoryConfigurationExtension extension) {
if (logger.isInfoEnabled()) {
logger.info(LogMessage.format("Bootstrapping Spring Data %s repositories in %s mode.",
extension.getModuleName(), this.configurationSource.getBootstrapMode().name()));
}
extension.registerBeansForRoot(registry, this.configurationSource);
RepositoryBeanDefinitionBuilder builder = new RepositoryBeanDefinitionBuilder(registry, extension,
this.configurationSource, this.resourceLoader, this.environment);
List<BeanComponentDefinition> definitions = new ArrayList<>();
StopWatch watch = new StopWatch();
if (logger.isDebugEnabled()) {
logger.debug(LogMessage.format("Scanning for %s repositories in packages %s.", extension.getModuleName(),
this.configurationSource.getBasePackages().stream().collect(Collectors.joining(", "))));
}
watch.start();
Collection<RepositoryConfiguration<RepositoryConfigurationSource>> configurations = extension
.getRepositoryConfigurations(this.configurationSource, this.resourceLoader, this.inMultiStoreMode);
Map<String, RepositoryConfiguration<?>> configurationsByRepositoryName = new HashMap<>(configurations.size());
for (RepositoryConfiguration<? extends RepositoryConfigurationSource> configuration : configurations) {
configurationsByRepositoryName.put(configuration.getRepositoryInterface(), configuration);
BeanDefinitionBuilder definitionBuilder = builder.build(configuration);
extension.postProcess(definitionBuilder, this.configurationSource);
if (this.isXml) {
extension.postProcess(definitionBuilder, (XmlRepositoryConfigurationSource) this.configurationSource);
}
else {
extension.postProcess(definitionBuilder,
(AnnotationRepositoryConfigurationSource) this.configurationSource);
}
AbstractBeanDefinition beanDefinition = definitionBuilder.getBeanDefinition();
beanDefinition.setResourceDescription(configuration.getResourceDescription());
String beanName = this.configurationSource.generateBeanName(beanDefinition);
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format(REPOSITORY_REGISTRATION, extension.getModuleName(), beanName,
configuration.getRepositoryInterface(), configuration.getRepositoryFactoryBeanClassName()));
}
beanDefinition.setAttribute(FACTORY_BEAN_OBJECT_TYPE, configuration.getRepositoryInterface());
registry.registerBeanDefinition(beanName, beanDefinition);
definitions.add(new BeanComponentDefinition(beanDefinition, beanName));
}
potentiallyLazifyRepositories(configurationsByRepositoryName, registry,
this.configurationSource.getBootstrapMode());
watch.stop();
if (logger.isInfoEnabled()) {
logger.info(LogMessage.format(
"Finished Spring Data repository scanning in %sms. Found %s %s repository interfaces.",
watch.getLastTaskTimeMillis(), configurations.size(), extension.getModuleName()));
}
return definitions;
}
/**
* Registers a {@link LazyRepositoryInjectionPointResolver} over the default
* {@link ContextAnnotationAutowireCandidateResolver} to make injection points of lazy
* repositories lazy, too. Will augment the
* {@link LazyRepositoryInjectionPointResolver}'s configuration if there already is
* one configured.
* @param configurations must not be {@literal null}.
* @param registry must not be {@literal null}.
*/
private static void potentiallyLazifyRepositories(Map<String, RepositoryConfiguration<?>> configurations,
BeanDefinitionRegistry registry, BootstrapMode mode) {
if (!DefaultListableBeanFactory.class.isInstance(registry) || mode.equals(BootstrapMode.DEFAULT)) {
return;
}
DefaultListableBeanFactory beanFactory = DefaultListableBeanFactory.class.cast(registry);
AutowireCandidateResolver resolver = beanFactory.getAutowireCandidateResolver();
if (!Arrays.asList(ContextAnnotationAutowireCandidateResolver.class, LazyRepositoryInjectionPointResolver.class)
.contains(resolver.getClass())) {
logger.warn(LogMessage.format(NON_DEFAULT_AUTOWIRE_CANDIDATE_RESOLVER, resolver.getClass().getName()));
return;
}
AutowireCandidateResolver newResolver = LazyRepositoryInjectionPointResolver.class.isInstance(resolver)
? LazyRepositoryInjectionPointResolver.class.cast(resolver).withAdditionalConfigurations(configurations)
: new LazyRepositoryInjectionPointResolver(configurations);
beanFactory.setAutowireCandidateResolver(newResolver);
if (mode.equals(BootstrapMode.DEFERRED)) {
logger.debug("Registering deferred repository initialization listener.");
beanFactory.registerSingleton(DeferredRepositoryInitializationListener.class.getName(),
new DeferredRepositoryInitializationListener(beanFactory));
}
}
/**
* Scans {@code repository.support} packages for implementations of
* {@link RepositoryFactorySupport}. Finding more than a single type is considered a
* multi-store configuration scenario which will trigger stricter repository scanning.
* @return
*/
private boolean multipleStoresDetected() {
boolean multipleModulesFound = SpringFactoriesLoader
.loadFactoryNames(RepositoryFactorySupport.class, this.resourceLoader.getClassLoader()).size() > 1;
if (multipleModulesFound) {
logger.info(MULTIPLE_MODULES);
}
return multipleModulesFound;
}
/**
* Customer {@link ContextAnnotationAutowireCandidateResolver} that also considers all
* injection points for lazy repositories lazy.
*
* @since 2.1
*/
static class LazyRepositoryInjectionPointResolver extends ContextAnnotationAutowireCandidateResolver {
private static final Log logger = LogFactory.getLog(LazyRepositoryInjectionPointResolver.class);
private final Map<String, RepositoryConfiguration<?>> configurations;
public LazyRepositoryInjectionPointResolver(Map<String, RepositoryConfiguration<?>> configurations) {
this.configurations = configurations;
}
/**
* Returns a new {@link LazyRepositoryInjectionPointResolver} that will have its
* configurations augmented with the given ones.
* @param configurations must not be {@literal null}.
* @return
*/
LazyRepositoryInjectionPointResolver withAdditionalConfigurations(
Map<String, RepositoryConfiguration<?>> configurations) {
Map<String, RepositoryConfiguration<?>> map = new HashMap<>(this.configurations);
map.putAll(configurations);
return new LazyRepositoryInjectionPointResolver(map);
}
@Override
protected boolean isLazy(DependencyDescriptor descriptor) {
Class<?> type = descriptor.getDependencyType();
RepositoryConfiguration<?> configuration = this.configurations.get(type.getName());
if (configuration == null) {
return super.isLazy(descriptor);
}
boolean lazyInit = configuration.isLazyInit();
if (lazyInit) {
logger.debug(LogMessage.format("Creating lazy injection proxy for %s…",
configuration.getRepositoryInterface()));
}
return lazyInit;
}
}
}