-
Notifications
You must be signed in to change notification settings - Fork 40.2k
/
JavaBeanBinder.java
434 lines (369 loc) · 12.6 KB
/
JavaBeanBinder.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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*
* Copyright 2012-2023 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.boot.context.properties.bind;
import java.beans.Introspector;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.context.properties.bind.Binder.Context;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertyState;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
/**
* {@link DataObjectBinder} for mutable Java Beans.
*
* @author Phillip Webb
* @author Madhura Bhave
* @author Lasse Wulff
*/
class JavaBeanBinder implements DataObjectBinder {
static final JavaBeanBinder INSTANCE = new JavaBeanBinder();
@Override
public <T> T bind(ConfigurationPropertyName name, Bindable<T> target, Context context,
DataObjectPropertyBinder propertyBinder) {
boolean hasKnownBindableProperties = target.getValue() != null && hasKnownBindableProperties(name, context);
Bean<T> bean = Bean.get(target, hasKnownBindableProperties);
if (bean == null) {
return null;
}
BeanSupplier<T> beanSupplier = bean.getSupplier(target);
boolean bound = bind(propertyBinder, bean, beanSupplier, context);
return (bound ? beanSupplier.get() : null);
}
@Override
@SuppressWarnings("unchecked")
public <T> T create(Bindable<T> target, Context context) {
Class<T> type = (Class<T>) target.getType().resolve();
return (type != null) ? BeanUtils.instantiateClass(type) : null;
}
private boolean hasKnownBindableProperties(ConfigurationPropertyName name, Context context) {
for (ConfigurationPropertySource source : context.getSources()) {
if (source.containsDescendantOf(name) == ConfigurationPropertyState.PRESENT) {
return true;
}
}
return false;
}
private <T> boolean bind(DataObjectPropertyBinder propertyBinder, Bean<T> bean, BeanSupplier<T> beanSupplier,
Context context) {
boolean bound = false;
for (BeanProperty beanProperty : bean.getProperties().values()) {
bound |= bind(beanSupplier, propertyBinder, beanProperty);
context.clearConfigurationProperty();
}
return bound;
}
private <T> boolean bind(BeanSupplier<T> beanSupplier, DataObjectPropertyBinder propertyBinder,
BeanProperty property) {
String propertyName = determinePropertyName(property);
ResolvableType type = property.getType();
Supplier<Object> value = property.getValue(beanSupplier);
Annotation[] annotations = property.getAnnotations();
Object bound = propertyBinder.bindProperty(propertyName,
Bindable.of(type).withSuppliedValue(value).withAnnotations(annotations));
if (bound == null) {
return false;
}
if (property.isSettable()) {
property.setValue(beanSupplier, bound);
}
else if (value == null || !bound.equals(value.get())) {
throw new IllegalStateException("No setter found for property: " + property.getName());
}
return true;
}
private String determinePropertyName(BeanProperty property) {
return Arrays.stream((property.getAnnotations() != null) ? property.getAnnotations() : new Annotation[0])
.filter((annotation) -> annotation.annotationType() == Name.class)
.findFirst()
.map(Name.class::cast)
.map(Name::value)
.orElse(property.getName());
}
/**
* The properties of a bean that may be bound.
*/
static class BeanProperties {
private final Map<String, BeanProperty> properties = new LinkedHashMap<>();
private final ResolvableType type;
private final Class<?> resolvedType;
BeanProperties(ResolvableType type, Class<?> resolvedType) {
this.type = type;
this.resolvedType = resolvedType;
addProperties(resolvedType);
}
private void addProperties(Class<?> type) {
while (type != null && !Object.class.equals(type)) {
Method[] declaredMethods = getSorted(type, this::getDeclaredMethods, Method::getName);
Field[] declaredFields = getSorted(type, Class::getDeclaredFields, Field::getName);
addProperties(declaredMethods, declaredFields);
type = type.getSuperclass();
}
}
private Method[] getDeclaredMethods(Class<?> type) {
Method[] methods = type.getDeclaredMethods();
Set<Method> result = new LinkedHashSet<>(methods.length);
for (Method method : methods) {
result.add(BridgeMethodResolver.findBridgedMethod(method));
}
return result.toArray(new Method[0]);
}
private <S, E> E[] getSorted(S source, Function<S, E[]> elements, Function<E, String> name) {
E[] result = elements.apply(source);
Arrays.sort(result, Comparator.comparing(name));
return result;
}
protected void addProperties(Method[] declaredMethods, Field[] declaredFields) {
for (int i = 0; i < declaredMethods.length; i++) {
if (!isCandidate(declaredMethods[i])) {
declaredMethods[i] = null;
}
}
for (Method method : declaredMethods) {
addMethodIfPossible(method, "is", 0, BeanProperty::addGetter);
}
for (Method method : declaredMethods) {
addMethodIfPossible(method, "get", 0, BeanProperty::addGetter);
}
for (Method method : declaredMethods) {
addMethodIfPossible(method, "set", 1, BeanProperty::addSetter);
}
for (Field field : declaredFields) {
addField(field);
}
}
private boolean isCandidate(Method method) {
int modifiers = method.getModifiers();
return !Modifier.isPrivate(modifiers) && !Modifier.isProtected(modifiers) && !Modifier.isAbstract(modifiers)
&& !Modifier.isStatic(modifiers) && !method.isBridge()
&& !Object.class.equals(method.getDeclaringClass())
&& !Class.class.equals(method.getDeclaringClass()) && method.getName().indexOf('$') == -1;
}
private void addMethodIfPossible(Method method, String prefix, int parameterCount,
BiConsumer<BeanProperty, Method> consumer) {
if (method != null && method.getParameterCount() == parameterCount && method.getName().startsWith(prefix)
&& method.getName().length() > prefix.length()) {
String propertyName = Introspector.decapitalize(method.getName().substring(prefix.length()));
consumer.accept(this.properties.computeIfAbsent(propertyName, this::getBeanProperty), method);
}
}
private BeanProperty getBeanProperty(String name) {
return new BeanProperty(name, this.type);
}
private void addField(Field field) {
BeanProperty property = this.properties.get(field.getName());
if (property != null) {
property.addField(field);
}
}
protected final ResolvableType getType() {
return this.type;
}
protected final Class<?> getResolvedType() {
return this.resolvedType;
}
final Map<String, BeanProperty> getProperties() {
return this.properties;
}
static BeanProperties of(Bindable<?> bindable) {
ResolvableType type = bindable.getType();
Class<?> resolvedType = type.resolve(Object.class);
return new BeanProperties(type, resolvedType);
}
}
/**
* The bean being bound.
*
* @param <T> the bean type
*/
static class Bean<T> extends BeanProperties {
private static Bean<?> cached;
Bean(ResolvableType type, Class<?> resolvedType) {
super(type, resolvedType);
}
@SuppressWarnings("unchecked")
BeanSupplier<T> getSupplier(Bindable<T> target) {
return new BeanSupplier<>(() -> {
T instance = null;
if (target.getValue() != null) {
instance = target.getValue().get();
}
if (instance == null) {
instance = (T) BeanUtils.instantiateClass(getResolvedType());
}
return instance;
});
}
@SuppressWarnings("unchecked")
static <T> Bean<T> get(Bindable<T> bindable, boolean canCallGetValue) {
ResolvableType type = bindable.getType();
Class<?> resolvedType = type.resolve(Object.class);
Supplier<T> value = bindable.getValue();
T instance = null;
if (canCallGetValue && value != null) {
instance = value.get();
resolvedType = (instance != null) ? instance.getClass() : resolvedType;
}
if (instance == null && !isInstantiable(resolvedType)) {
return null;
}
Bean<?> bean = Bean.cached;
if (bean == null || !bean.isOfType(type, resolvedType)) {
bean = new Bean<>(type, resolvedType);
cached = bean;
}
return (Bean<T>) bean;
}
private static boolean isInstantiable(Class<?> type) {
if (type.isInterface()) {
return false;
}
try {
type.getDeclaredConstructor();
return true;
}
catch (Exception ex) {
return false;
}
}
private boolean isOfType(ResolvableType type, Class<?> resolvedType) {
if (getType().hasGenerics() || type.hasGenerics()) {
return getType().equals(type);
}
return getResolvedType() != null && getResolvedType().equals(resolvedType);
}
}
private static class BeanSupplier<T> implements Supplier<T> {
private final Supplier<T> factory;
private T instance;
BeanSupplier(Supplier<T> factory) {
this.factory = factory;
}
@Override
public T get() {
if (this.instance == null) {
this.instance = this.factory.get();
}
return this.instance;
}
}
/**
* A bean property being bound.
*/
static class BeanProperty {
private final String name;
private final ResolvableType declaringClassType;
private Method getter;
private Method setter;
private Field field;
BeanProperty(String name, ResolvableType declaringClassType) {
this.name = DataObjectPropertyName.toDashedForm(name);
this.declaringClassType = declaringClassType;
}
void addGetter(Method getter) {
if (this.getter == null || this.getter.getName().startsWith("is")) {
this.getter = getter;
}
}
void addSetter(Method setter) {
if (this.setter == null || isBetterSetter(setter)) {
this.setter = setter;
}
}
private boolean isBetterSetter(Method setter) {
return this.getter != null && this.getter.getReturnType().equals(setter.getParameterTypes()[0]);
}
void addField(Field field) {
if (this.field == null) {
this.field = field;
}
}
String getName() {
return this.name;
}
ResolvableType getType() {
if (this.setter != null) {
MethodParameter methodParameter = new MethodParameter(this.setter, 0);
return ResolvableType.forMethodParameter(methodParameter, this.declaringClassType);
}
MethodParameter methodParameter = new MethodParameter(this.getter, -1);
return ResolvableType.forMethodParameter(methodParameter, this.declaringClassType);
}
Annotation[] getAnnotations() {
try {
return (this.field != null) ? this.field.getDeclaredAnnotations() : null;
}
catch (Exception ex) {
return null;
}
}
Supplier<Object> getValue(Supplier<?> instance) {
if (this.getter == null) {
return null;
}
return () -> {
try {
this.getter.setAccessible(true);
return this.getter.invoke(instance.get());
}
catch (Exception ex) {
if (isUninitializedKotlinProperty(ex)) {
return null;
}
throw new IllegalStateException("Unable to get value for property " + this.name, ex);
}
};
}
private boolean isUninitializedKotlinProperty(Exception ex) {
return (ex instanceof InvocationTargetException invocationTargetException)
&& "kotlin.UninitializedPropertyAccessException"
.equals(invocationTargetException.getTargetException().getClass().getName());
}
boolean isSettable() {
return this.setter != null;
}
void setValue(Supplier<?> instance, Object value) {
try {
this.setter.setAccessible(true);
this.setter.invoke(instance.get(), value);
}
catch (Exception ex) {
throw new IllegalStateException("Unable to set value for property " + this.name, ex);
}
}
Method getGetter() {
return this.getter;
}
Method getSetter() {
return this.setter;
}
}
}