forked from spring-projects/spring-framework
/
BeanDefinitionPropertiesCodeGenerator.java
328 lines (284 loc) · 12.1 KB
/
BeanDefinitionPropertiesCodeGenerator.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
/*
* Copyright 2002-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.beans.factory.aot;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import org.springframework.aot.generate.GeneratedMethods;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.AutowireCandidateQualifier;
import org.springframework.beans.factory.support.InstanceSupplier;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.javapoet.CodeBlock;
import org.springframework.javapoet.CodeBlock.Builder;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* Internal code generator to set {@link RootBeanDefinition} properties.
*
* <p>Generates code in the following form:<pre class="code">
* beanDefinition.setPrimary(true);
* beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
* ...
* </pre>
*
* <p>The generated code expects the following variables to be available:
* <ul>
* <li>{@code beanDefinition}: the {@link RootBeanDefinition} to configure</li>
* </ul>
*
* <p>Note that this generator does <b>not</b> set the {@link InstanceSupplier}.
*
* @author Phillip Webb
* @author Stephane Nicoll
* @author Sam Brannen
* @since 6.0
*/
class BeanDefinitionPropertiesCodeGenerator {
private static final RootBeanDefinition DEFAULT_BEAN_DEFINITION = new RootBeanDefinition();
private static final String BEAN_DEFINITION_VARIABLE = BeanRegistrationCodeFragments.BEAN_DEFINITION_VARIABLE;
private final RuntimeHints hints;
private final Predicate<String> attributeFilter;
private final BeanDefinitionPropertyValueCodeGenerator valueCodeGenerator;
BeanDefinitionPropertiesCodeGenerator(RuntimeHints hints,
Predicate<String> attributeFilter, GeneratedMethods generatedMethods,
BiFunction<String, Object, CodeBlock> customValueCodeGenerator) {
this.hints = hints;
this.attributeFilter = attributeFilter;
this.valueCodeGenerator = new BeanDefinitionPropertyValueCodeGenerator(generatedMethods,
(object, type) -> customValueCodeGenerator.apply(PropertyNamesStack.peek(), object));
}
CodeBlock generateCode(RootBeanDefinition beanDefinition) {
CodeBlock.Builder code = CodeBlock.builder();
addStatementForValue(code, beanDefinition, BeanDefinition::isPrimary,
"$L.setPrimary($L)");
addStatementForValue(code, beanDefinition, BeanDefinition::getScope,
this::hasScope, "$L.setScope($S)");
addStatementForValue(code, beanDefinition, BeanDefinition::getDependsOn,
this::hasDependsOn, "$L.setDependsOn($L)", this::toStringVarArgs);
addStatementForValue(code, beanDefinition, BeanDefinition::isAutowireCandidate,
"$L.setAutowireCandidate($L)");
addStatementForValue(code, beanDefinition, BeanDefinition::getRole,
this::hasRole, "$L.setRole($L)", this::toRole);
addStatementForValue(code, beanDefinition, AbstractBeanDefinition::getLazyInit,
"$L.setLazyInit($L)");
addStatementForValue(code, beanDefinition, AbstractBeanDefinition::isSynthetic,
"$L.setSynthetic($L)");
addInitDestroyMethods(code, beanDefinition, beanDefinition.getInitMethodNames(),
"$L.setInitMethodNames($L)");
addInitDestroyMethods(code, beanDefinition, beanDefinition.getDestroyMethodNames(),
"$L.setDestroyMethodNames($L)");
addConstructorArgumentValues(code, beanDefinition);
addPropertyValues(code, beanDefinition);
addAttributes(code, beanDefinition);
addQualifiers(code, beanDefinition);
return code.build();
}
private void addInitDestroyMethods(Builder code,
AbstractBeanDefinition beanDefinition, @Nullable String[] methodNames, String format) {
if (!ObjectUtils.isEmpty(methodNames)) {
Class<?> beanType = ClassUtils.getUserClass(beanDefinition.getResolvableType().toClass());
Arrays.stream(methodNames).forEach(methodName -> addInitDestroyHint(beanType, methodName));
CodeBlock arguments = Arrays.stream(methodNames)
.map(name -> CodeBlock.of("$S", name))
.collect(CodeBlock.joining(", "));
code.addStatement(format, BEAN_DEFINITION_VARIABLE, arguments);
}
}
private void addInitDestroyHint(Class<?> beanUserClass, String methodName) {
// TODO Handle fully-qualified method names
Method method = ReflectionUtils.findMethod(beanUserClass, methodName);
if (method != null) {
this.hints.reflection().registerMethod(method, ExecutableMode.INVOKE);
}
}
private void addConstructorArgumentValues(CodeBlock.Builder code,
BeanDefinition beanDefinition) {
Map<Integer, ValueHolder> argumentValues = beanDefinition
.getConstructorArgumentValues().getIndexedArgumentValues();
if (!argumentValues.isEmpty()) {
argumentValues.forEach((index, valueHolder) -> {
CodeBlock valueCode = generateValue(valueHolder.getName(), valueHolder.getValue());
code.addStatement(
"$L.getConstructorArgumentValues().addIndexedArgumentValue($L, $L)",
BEAN_DEFINITION_VARIABLE, index, valueCode);
});
}
}
private void addPropertyValues(CodeBlock.Builder code,
RootBeanDefinition beanDefinition) {
MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
if (!propertyValues.isEmpty()) {
for (PropertyValue propertyValue : propertyValues) {
String name = propertyValue.getName();
CodeBlock valueCode = generateValue(name, propertyValue.getValue());
code.addStatement("$L.getPropertyValues().addPropertyValue($S, $L)",
BEAN_DEFINITION_VARIABLE, propertyValue.getName(), valueCode);
}
Class<?> infrastructureType = getInfrastructureType(beanDefinition);
if (infrastructureType != Object.class) {
Map<String, Method> writeMethods = getWriteMethods(infrastructureType);
for (PropertyValue propertyValue : propertyValues) {
Method writeMethod = writeMethods.get(propertyValue.getName());
if (writeMethod != null) {
this.hints.reflection().registerMethod(writeMethod, ExecutableMode.INVOKE);
}
}
}
}
}
private void addQualifiers(CodeBlock.Builder code,
RootBeanDefinition beanDefinition) {
Set<AutowireCandidateQualifier> qualifiers = beanDefinition.getQualifiers();
if (!qualifiers.isEmpty()) {
for (AutowireCandidateQualifier qualifier : qualifiers) {
Collection<CodeBlock> arguments = new ArrayList<>();
arguments.add(CodeBlock.of("$S", qualifier.getTypeName()));
Object qualifierValue = qualifier.getAttribute(AutowireCandidateQualifier.VALUE_KEY);
if (qualifierValue != null) {
arguments.add(generateValue("value", qualifierValue));
}
code.addStatement("$L.addQualifier(new $T($L))", BEAN_DEFINITION_VARIABLE,
AutowireCandidateQualifier.class, CodeBlock.join(arguments, ", "));
}
}
}
private CodeBlock generateValue(@Nullable String name, @Nullable Object value) {
try {
PropertyNamesStack.push(name);
return this.valueCodeGenerator.generateCode(value);
}
finally {
PropertyNamesStack.pop();
}
}
private Class<?> getInfrastructureType(RootBeanDefinition beanDefinition) {
if (beanDefinition.hasBeanClass()) {
Class<?> beanClass = beanDefinition.getBeanClass();
if (FactoryBean.class.isAssignableFrom(beanClass)) {
return beanClass;
}
}
return ClassUtils.getUserClass(beanDefinition.getResolvableType().toClass());
}
private Map<String, Method> getWriteMethods(Class<?> clazz) {
Map<String, Method> writeMethods = new HashMap<>();
for (PropertyDescriptor propertyDescriptor : BeanUtils.getPropertyDescriptors(clazz)) {
writeMethods.put(propertyDescriptor.getName(), propertyDescriptor.getWriteMethod());
}
return Collections.unmodifiableMap(writeMethods);
}
private void addAttributes(CodeBlock.Builder code, BeanDefinition beanDefinition) {
String[] attributeNames = beanDefinition.attributeNames();
if (!ObjectUtils.isEmpty(attributeNames)) {
for (String attributeName : attributeNames) {
if (this.attributeFilter.test(attributeName)) {
CodeBlock value = this.valueCodeGenerator
.generateCode(beanDefinition.getAttribute(attributeName));
code.addStatement("$L.setAttribute($S, $L)",
BEAN_DEFINITION_VARIABLE, attributeName, value);
}
}
}
}
private boolean hasScope(String defaultValue, String actualValue) {
return StringUtils.hasText(actualValue)
&& !ConfigurableBeanFactory.SCOPE_SINGLETON.equals(actualValue);
}
private boolean hasDependsOn(String[] defaultValue, String[] actualValue) {
return !ObjectUtils.isEmpty(actualValue);
}
private boolean hasRole(int defaultValue, int actualValue) {
return actualValue != BeanDefinition.ROLE_APPLICATION;
}
private CodeBlock toStringVarArgs(String[] strings) {
return Arrays.stream(strings).map(string -> CodeBlock.of("$S", string))
.collect(CodeBlock.joining(","));
}
private Object toRole(int value) {
return switch (value) {
case BeanDefinition.ROLE_INFRASTRUCTURE -> CodeBlock.builder()
.add("$T.ROLE_INFRASTRUCTURE", BeanDefinition.class).build();
case BeanDefinition.ROLE_SUPPORT -> CodeBlock.builder()
.add("$T.ROLE_SUPPORT", BeanDefinition.class).build();
default -> value;
};
}
private <B extends BeanDefinition, T> void addStatementForValue(
CodeBlock.Builder code, BeanDefinition beanDefinition,
Function<B, T> getter, String format) {
addStatementForValue(code, beanDefinition, getter,
(defaultValue, actualValue) -> !Objects.equals(defaultValue, actualValue),
format);
}
private <B extends BeanDefinition, T> void addStatementForValue(
CodeBlock.Builder code, BeanDefinition beanDefinition,
Function<B, T> getter, BiPredicate<T, T> filter, String format) {
addStatementForValue(code, beanDefinition, getter, filter, format,
actualValue -> actualValue);
}
@SuppressWarnings("unchecked")
private <B extends BeanDefinition, T> void addStatementForValue(
CodeBlock.Builder code, BeanDefinition beanDefinition,
Function<B, T> getter, BiPredicate<T, T> filter, String format,
Function<T, Object> formatter) {
T defaultValue = getter.apply((B) DEFAULT_BEAN_DEFINITION);
T actualValue = getter.apply((B) beanDefinition);
if (filter.test(defaultValue, actualValue)) {
code.addStatement(format, BEAN_DEFINITION_VARIABLE,
formatter.apply(actualValue));
}
}
static class PropertyNamesStack {
private static final ThreadLocal<ArrayDeque<String>> threadLocal = ThreadLocal.withInitial(ArrayDeque::new);
static void push(@Nullable String name) {
String valueToSet = (name != null) ? name : "";
threadLocal.get().push(valueToSet);
}
static void pop() {
threadLocal.get().pop();
}
@Nullable
static String peek() {
String value = threadLocal.get().peek();
return ("".equals(value) ? null : value);
}
}
}