-
Notifications
You must be signed in to change notification settings - Fork 662
/
RepositoryFactorySupport.java
395 lines (330 loc) · 13 KB
/
RepositoryFactorySupport.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/*
* Copyright 2008-2013 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.repository.core.support;
import static org.springframework.util.ReflectionUtils.*;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.core.GenericTypeResolver;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.EntityInformation;
import org.springframework.data.repository.core.NamedQueries;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
import org.springframework.data.repository.query.QueryMethod;
import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.data.repository.util.ClassUtils;
import org.springframework.util.Assert;
/**
* Factory bean to create instances of a given repository interface. Creates a proxy implementing the configured
* repository interface and apply an advice handing the control to the {@code QueryExecuterMethodInterceptor}. Query
* detection strategy can be configured by setting {@link QueryLookupStrategy.Key}.
*
* @author Oliver Gierke
*/
public abstract class RepositoryFactorySupport {
private final List<RepositoryProxyPostProcessor> postProcessors = new ArrayList<RepositoryProxyPostProcessor>();
private QueryLookupStrategy.Key queryLookupStrategyKey;
private List<QueryCreationListener<?>> queryPostProcessors = new ArrayList<QueryCreationListener<?>>();
private NamedQueries namedQueries = PropertiesBasedNamedQueries.EMPTY;
private QueryCollectingQueryCreationListener collectingListener = new QueryCollectingQueryCreationListener();
public RepositoryFactorySupport() {
this.queryPostProcessors.add(collectingListener);
}
/**
* Sets the strategy of how to lookup a query to execute finders.
*
* @param key
*/
public void setQueryLookupStrategyKey(Key key) {
this.queryLookupStrategyKey = key;
}
/**
* Configures a {@link NamedQueries} instance to be handed to the {@link QueryLookupStrategy} for query creation.
*
* @param namedQueries the namedQueries to set
*/
public void setNamedQueries(NamedQueries namedQueries) {
this.namedQueries = namedQueries == null ? PropertiesBasedNamedQueries.EMPTY : namedQueries;
}
/**
* Adds a {@link QueryCreationListener} to the factory to plug in functionality triggered right after creation of
* {@link RepositoryQuery} instances.
*
* @param listener
*/
public void addQueryCreationListener(QueryCreationListener<?> listener) {
Assert.notNull(listener);
this.queryPostProcessors.add(listener);
}
/**
* Adds {@link RepositoryProxyPostProcessor}s to the factory to allow manipulation of the {@link ProxyFactory} before
* the proxy gets created. Note that the {@link QueryExecutorMethodInterceptor} will be added to the proxy
* <em>after</em> the {@link RepositoryProxyPostProcessor}s are considered.
*
* @param processor
*/
public void addRepositoryProxyPostProcessor(RepositoryProxyPostProcessor processor) {
Assert.notNull(processor);
this.postProcessors.add(processor);
}
/**
* Returns a repository instance for the given interface.
*
* @param <T>
* @param repositoryInterface
* @return
*/
public <T> T getRepository(Class<T> repositoryInterface) {
return getRepository(repositoryInterface, null);
}
/**
* Returns a repository instance for the given interface backed by an instance providing implementation logic for
* custom logic.
*
* @param <T>
* @param repositoryInterface
* @param customImplementation
* @return
*/
@SuppressWarnings({ "unchecked" })
public <T> T getRepository(Class<T> repositoryInterface, Object customImplementation) {
RepositoryMetadata metadata = getRepositoryMetadata(repositoryInterface);
Class<?> customImplementationClass = null == customImplementation ? null : customImplementation.getClass();
RepositoryInformation information = getRepositoryInformation(metadata, customImplementationClass);
validate(information, customImplementation);
Object target = getTargetRepository(information);
// Create proxy
ProxyFactory result = new ProxyFactory();
result.setTarget(target);
result.setInterfaces(new Class[] { repositoryInterface, Repository.class });
for (RepositoryProxyPostProcessor processor : postProcessors) {
processor.postProcess(result);
}
result.addAdvice(new QueryExecutorMethodInterceptor(information, customImplementation, target));
return (T) result.getProxy();
}
/**
* Returns the {@link RepositoryMetadata} for the given repository interface.
*
* @param repositoryInterface
* @return
*/
RepositoryMetadata getRepositoryMetadata(Class<?> repositoryInterface) {
return Repository.class.isAssignableFrom(repositoryInterface) ? new DefaultRepositoryMetadata(repositoryInterface)
: new AnnotationRepositoryMetadata(repositoryInterface);
}
/**
* Returns the {@link RepositoryInformation} for the given repository interface.
*
* @param metadata
* @param customImplementationClass
* @return
*/
protected RepositoryInformation getRepositoryInformation(RepositoryMetadata metadata,
Class<?> customImplementationClass) {
return new DefaultRepositoryInformation(metadata, getRepositoryBaseClass(metadata), customImplementationClass);
}
protected List<QueryMethod> getQueryMethods() {
return collectingListener.getQueryMethods();
}
/**
* Returns the {@link EntityInformation} for the given domain class.
*
* @param <T> the entity type
* @param <ID> the id type
* @param domainClass
* @return
*/
public abstract <T, ID extends Serializable> EntityInformation<T, ID> getEntityInformation(Class<T> domainClass);
/**
* Create a repository instance as backing for the query proxy.
*
* @param metadata
* @return
*/
protected abstract Object getTargetRepository(RepositoryMetadata metadata);
/**
* Returns the base class backing the actual repository instance. Make sure
* {@link #getTargetRepository(RepositoryMetadata)} returns an instance of this class.
*
* @param metadata
* @return
*/
protected abstract Class<?> getRepositoryBaseClass(RepositoryMetadata metadata);
/**
* Returns the {@link QueryLookupStrategy} for the given {@link Key}.
*
* @param key can be {@literal null}
* @return the {@link QueryLookupStrategy} to use or {@literal null} if no queries should be looked up.
*/
protected QueryLookupStrategy getQueryLookupStrategy(Key key) {
return null;
}
/**
* Validates the given repository interface as well as the given custom implementation.
*
* @param repositoryInformation
* @param customImplementation
*/
private void validate(RepositoryInformation repositoryInformation, Object customImplementation) {
if (null == customImplementation && repositoryInformation.hasCustomMethod()) {
throw new IllegalArgumentException(String.format(
"You have custom methods in %s but not provided a custom implementation!",
repositoryInformation.getRepositoryInterface()));
}
validate(repositoryInformation);
}
protected void validate(RepositoryMetadata repositoryMetadata) {
}
/**
* This {@code MethodInterceptor} intercepts calls to methods of the custom implementation and delegates the to it if
* configured. Furthermore it resolves method calls to finders and triggers execution of them. You can rely on having
* a custom repository implementation instance set if this returns true.
*
* @author Oliver Gierke
*/
public class QueryExecutorMethodInterceptor implements MethodInterceptor {
private final Map<Method, RepositoryQuery> queries = new ConcurrentHashMap<Method, RepositoryQuery>();
private final Object customImplementation;
private final RepositoryInformation repositoryInformation;
private final Object target;
/**
* Creates a new {@link QueryExecutorMethodInterceptor}. Builds a model of {@link QueryMethod}s to be invoked on
* execution of repository interface methods.
*/
public QueryExecutorMethodInterceptor(RepositoryInformation repositoryInformation, Object customImplementation,
Object target) {
this.repositoryInformation = repositoryInformation;
this.customImplementation = customImplementation;
this.target = target;
QueryLookupStrategy lookupStrategy = getQueryLookupStrategy(queryLookupStrategyKey);
Iterable<Method> queryMethods = repositoryInformation.getQueryMethods();
if (lookupStrategy == null) {
if (queryMethods.iterator().hasNext()) {
throw new IllegalStateException("You have defined query method in the repository but "
+ "you don't have no query lookup strategy defined. The "
+ "infrastructure apparently does not support query methods!");
}
return;
}
for (Method method : queryMethods) {
RepositoryQuery query = lookupStrategy.resolveQuery(method, repositoryInformation, namedQueries);
invokeListeners(query);
queries.put(method, query);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void invokeListeners(RepositoryQuery query) {
for (QueryCreationListener listener : queryPostProcessors) {
Class<?> typeArgument = GenericTypeResolver.resolveTypeArgument(listener.getClass(),
QueryCreationListener.class);
if (typeArgument != null && typeArgument.isAssignableFrom(query.getClass())) {
listener.onCreation(query);
}
}
}
/*
* (non-Javadoc)
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
if (isCustomMethodInvocation(invocation)) {
Method actualMethod = repositoryInformation.getTargetClassMethod(method);
makeAccessible(actualMethod);
return executeMethodOn(customImplementation, actualMethod, invocation.getArguments());
}
if (hasQueryFor(method)) {
return queries.get(method).execute(invocation.getArguments());
}
// Lookup actual method as it might be redeclared in the interface
// and we have to use the repository instance nevertheless
Method actualMethod = repositoryInformation.getTargetClassMethod(method);
return executeMethodOn(target, actualMethod, invocation.getArguments());
}
/**
* Executes the given method on the given target. Correctly unwraps exceptions not caused by the reflection magic.
*
* @param target
* @param method
* @param parameters
* @return
* @throws Throwable
*/
private Object executeMethodOn(Object target, Method method, Object[] parameters) throws Throwable {
try {
return method.invoke(target, parameters);
} catch (Exception e) {
ClassUtils.unwrapReflectionException(e);
}
throw new IllegalStateException("Should not occur!");
}
/**
* Returns whether we know of a query to execute for the given {@link Method};
*
* @param method
* @return
*/
private boolean hasQueryFor(Method method) {
return queries.containsKey(method);
}
/**
* Returns whether the given {@link MethodInvocation} is considered to be targeted as an invocation of a custom
* method.
*
* @param method
* @return
*/
private boolean isCustomMethodInvocation(MethodInvocation invocation) {
if (null == customImplementation) {
return false;
}
return repositoryInformation.isCustomMethod(invocation.getMethod());
}
}
/**
* {@link QueryCreationListener} collecting the {@link QueryMethod}s created for all query methods of the repository
* interface.
*
* @author Oliver Gierke
*/
private static class QueryCollectingQueryCreationListener implements QueryCreationListener<RepositoryQuery> {
private List<QueryMethod> queryMethods = new ArrayList<QueryMethod>();
/**
* Returns all {@link QueryMethod}s.
*
* @return
*/
public List<QueryMethod> getQueryMethods() {
return queryMethods;
}
/* (non-Javadoc)
* @see org.springframework.data.repository.core.support.QueryCreationListener#onCreation(org.springframework.data.repository.query.RepositoryQuery)
*/
public void onCreation(RepositoryQuery query) {
this.queryMethods.add(query.getQueryMethod());
}
}
}