This repository has been archived by the owner on Jan 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
ConfigurationClassObjectDefinitionReader.cs
318 lines (275 loc) · 13.2 KB
/
ConfigurationClassObjectDefinitionReader.cs
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
#region License
/*
* Copyright © 2010-2011 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.
*/
#endregion
#region
using System;
using System.Collections.Generic;
using System.Reflection;
using Common.Logging;
using Spring.Core.TypeResolution;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Parsing;
using Spring.Objects.Factory.Support;
using Spring.Stereotype;
#endregion
namespace Spring.Context.Attributes
{
/// <summary>
/// Reads the class with the <see cref="ConfigurationAttribute"/> applied and converts it into an <see cref="Spring.Objects.Factory.Config.IObjectDefinition"/> instance.
/// </summary>
public class ConfigurationClassObjectDefinitionReader
{
private readonly ILog _logger = LogManager.GetLogger(typeof(ConfigurationClassObjectDefinitionReader));
private IProblemReporter _problemReporter;
private IObjectDefinitionRegistry _registry;
/// <summary>
/// Initializes a new instance of the ConfigurationClassObjectDefinitionReader class.
/// </summary>
/// <param name="registry"></param>
/// <param name="problemReporter"></param>
public ConfigurationClassObjectDefinitionReader(IObjectDefinitionRegistry registry,
IProblemReporter problemReporter)
{
_registry = registry;
_problemReporter = problemReporter;
}
private static bool HasAttributeOnMethods(Type objectType, Type attributeType)
{
Collections.Generic.ISet<MethodInfo> methods = ConfigurationClassParser.GetAllMethodsWithCustomAttributeForClass(objectType,
attributeType);
foreach (MethodInfo method in methods)
{
if (Attribute.GetCustomAttribute(method, attributeType) != null)
{
return true;
}
}
return false;
}
/// <summary>
/// Loads the object definitions.
/// </summary>
/// <param name="configurationModel">The configuration model.</param>
public void LoadObjectDefinitions(Collections.Generic.ISet<ConfigurationClass> configurationModel)
{
foreach (ConfigurationClass configClass in configurationModel)
{
LoadObjectDefinitionsForConfigurationClass(configClass);
}
}
private void LoadObjectDefinitionForConfigurationClassIfNecessary(ConfigurationClass configClass)
{
if (configClass.ObjectName != null)
{
// a Object definition already exists for this configuration class -> nothing to do
return;
}
// no Object definition exists yet -> this must be an imported configuration class ([Import]).
GenericObjectDefinition configObjectDef = new GenericObjectDefinition();
String className = configClass.ConfigurationClassType.Name;
configObjectDef.ObjectTypeName = className;
configObjectDef.ObjectType = configClass.ConfigurationClassType;
if (CheckConfigurationClassCandidate(configClass.ConfigurationClassType))
{
String configObjectName = ObjectDefinitionReaderUtils.RegisterWithGeneratedName(configObjectDef,
_registry);
configClass.ObjectName = configObjectName;
if (_logger.IsDebugEnabled)
{
_logger.Debug(String.Format("Registered object definition for imported [Configuration] class {0}",
configObjectName));
}
}
}
/// <summary>
/// Checks the class to see if it is a candidate to be a <see cref="ConfigurationAttribute"/> source.
/// </summary>
/// <param name="objectDefinition">The object definition.</param>
/// <returns></returns>
public static bool CheckConfigurationClassCandidate(IObjectDefinition objectDefinition)
{
Type objectType = null;
if (objectDefinition is AbstractObjectDefinition)
{
AbstractObjectDefinition definition = (AbstractObjectDefinition)objectDefinition;
if (definition.HasObjectType)
{
objectType = definition.ObjectType;
}
else
{
if (definition.ObjectTypeName != null && !definition.IsAbstract)
{
objectType = TypeResolutionUtils.ResolveType(definition.ObjectTypeName);
}
}
if (objectType != null)
{
if (Attribute.GetCustomAttribute(objectType, typeof(ConfigurationAttribute)) != null)
{
return true;
}
if (Attribute.GetCustomAttribute(objectType, typeof(ComponentAttribute)) != null ||
HasAttributeOnMethods(objectType, typeof(DefinitionAttribute)))
{
return true;
}
}
}
return false;
}
private bool CheckConfigurationClassCandidate(Type type)
{
if (type != null)
{
return (Attribute.GetCustomAttribute(type, typeof(ConfigurationAttribute)) != null);
}
return false;
}
private void LoadObjectDefinitionsForConfigurationClass(ConfigurationClass configClass)
{
LoadObjectDefinitionForConfigurationClassIfNecessary(configClass);
foreach (ConfigurationClassMethod method in configClass.Methods)
{
LoadObjectDefinitionsForModelMethod(method);
}
LoadObjectDefinitionsFromImportedResources(configClass.ImportedResources);
}
private void LoadObjectDefinitionsForModelMethod(ConfigurationClassMethod method)
{
ConfigurationClass configClass = method.ConfigurationClass;
MethodInfo metadata = method.MethodMetadata;
RootObjectDefinition objDef = new ConfigurationClassObjectDefinition();
objDef.FactoryObjectName = configClass.ObjectName;
objDef.FactoryMethodName = metadata.Name;
objDef.AutowireMode = Objects.Factory.Config.AutoWiringMode.Constructor;
// consider name and any aliases
//Dictionary<String, Object> ObjectAttributes = metadata.getAnnotationAttributes(Object.class.getName());
object[] objectAttributes = metadata.GetCustomAttributes(typeof(DefinitionAttribute), true);
List<string> names = new List<string>();
foreach (object t in objectAttributes)
{
string[] namesAndAliases = ((DefinitionAttribute)t).NamesToArray;
if (namesAndAliases != null)
{
names.Add(metadata.Name);
}
else
{
namesAndAliases = new[] { metadata.Name };
}
names.AddRange(namesAndAliases);
}
string objectName = (names.Count > 0 ? names[0] : method.MethodMetadata.Name);
for (int i = 1; i < names.Count; i++)
{
_registry.RegisterAlias(objectName, names[i]);
}
// has this already been overridden (e.g. via XML)?
if (_registry.ContainsObjectDefinition(objectName))
{
IObjectDefinition existingObjectDef = _registry.GetObjectDefinition(objectName);
// is the existing Object definition one that was created from a configuration class?
if (!(existingObjectDef is ConfigurationClassObjectDefinition))
{
// no -> then it's an external override, probably XML
// overriding is legal, return immediately
if (_logger.IsDebugEnabled)
{
_logger.Debug(
String.Format("Skipping loading Object definition for {0}: a definition for object " +
"'{1}' already exists. This is likely due to an override in XML.", method,
objectName));
}
return;
}
}
//TODO: container does not presently support the concept of Primary object defintion for type resolution
//if (Attribute.GetCustomAttribute(metadata, typeof(PrimaryAttribute)) != null)
//{
// ObjectDef.isPrimary = true;
//}
// is this Object to be instantiated lazily?
if (Attribute.GetCustomAttribute(metadata, typeof(LazyAttribute)) != null)
{
objDef.IsLazyInit =
(Attribute.GetCustomAttribute(metadata, typeof(LazyAttribute)) as LazyAttribute).LazyInitialize;
}
if (Attribute.GetCustomAttribute(metadata, typeof(DependsOnAttribute)) != null)
{
objDef.DependsOn =
(Attribute.GetCustomAttribute(metadata, typeof(DependsOnAttribute)) as DependsOnAttribute).Name;
}
//TODO: container does not presently support autowiring to the degree needed to support this feature as of yet
//Autowire autowire = (Autowire) ObjectAttributes.get("autowire");
//if (autowire.isAutowire()) {
// ObjectDef.setAutowireMode(autowire.value());
//}
if (Attribute.GetCustomAttribute(metadata, typeof(DefinitionAttribute)) != null)
{
objDef.InitMethodName =
(Attribute.GetCustomAttribute(metadata, typeof(DefinitionAttribute)) as DefinitionAttribute).
InitMethod;
objDef.DestroyMethodName =
(Attribute.GetCustomAttribute(metadata, typeof(DefinitionAttribute)) as DefinitionAttribute).
DestroyMethod;
}
// consider scoping
if (Attribute.GetCustomAttribute(metadata, typeof(ScopeAttribute)) != null)
{
objDef.Scope =
(Attribute.GetCustomAttribute(metadata, typeof(ScopeAttribute)) as ScopeAttribute).ObjectScope.ToString();
}
if (_logger.IsDebugEnabled)
{
_logger.Debug(String.Format("Registering Object definition for [Definition] method {0}.{1}()",
configClass.ConfigurationClassType.Name, objectName));
}
_registry.RegisterObjectDefinition(objectName, objDef);
}
private void LoadObjectDefinitionsFromImportedResources(IEnumerable<KeyValuePair<string, Type>> importedResources)
{
IDictionary<Type, IObjectDefinitionReader> readerInstanceCache =
new Dictionary<Type, IObjectDefinitionReader>();
foreach (KeyValuePair<string, Type> entry in importedResources)
{
String resource = entry.Key;
Type readerClass = entry.Value;
if (!readerInstanceCache.ContainsKey(readerClass))
{
try
{
IObjectDefinitionReader readerInstance =
(IObjectDefinitionReader)Activator.CreateInstance(readerClass, _registry);
readerInstanceCache.Add(readerClass, readerInstance);
}
catch (Exception)
{
throw new InvalidOperationException(
String.Format("Could not instantiate IObjectDefinitionReader class {0}",
readerClass.FullName));
}
}
IObjectDefinitionReader reader = readerInstanceCache[readerClass];
reader.LoadObjectDefinitions(resource);
}
}
private class ConfigurationClassObjectDefinition : RootObjectDefinition
{
}
}
}