revised support for annotated factory methods (merged @FactoryMethod functionality into JavaConfig facility)
This commit is contained in:
@@ -1,122 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.parsing.FailFastProblemReporter;
|
||||
import org.springframework.beans.factory.parsing.ProblemReporter;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
|
||||
|
||||
/**
|
||||
* Abstract superclass for processing {@link Configuration}-annotated classes and registering
|
||||
* bean definitions based on {@link Bean}-annotated methods within those classes.
|
||||
*
|
||||
* <p>Provides template method {@link #processConfigBeanDefinitions()} that orchestrates calling each
|
||||
* of several abstract methods to be overriden by concrete implementations that allow for
|
||||
* customizing how {@link Configuration} classes are found ({@link #getConfigurationBeanDefinitions}),
|
||||
* customizing the creation of a {@link ConfigurationClassParser} ({@link #createConfigurationParser}),
|
||||
* and customizing {@link ConfigurationModel} validation logic ({@link #validateModel}).
|
||||
*
|
||||
* <p>This class was expressly designed with tooling in mind. Spring IDE will maintain it's
|
||||
* own implementation of this class but still take advantage of the generic parsing algorithm
|
||||
* defined here by {@link #processConfigBeanDefinitions()}.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @since 3.0
|
||||
* @see Configuration
|
||||
* @see ConfigurationClassPostProcessor
|
||||
*/
|
||||
public abstract class AbstractConfigurationClassProcessor {
|
||||
|
||||
/**
|
||||
* Used to register any problems detected with {@link Configuration} or {@link Bean}
|
||||
* declarations. For instance, a Bean method marked as {@literal final} is illegal
|
||||
* and would be reported as a problem. Defaults to {@link FailFastProblemReporter},
|
||||
* but is overridable with {@link #setProblemReporter}
|
||||
*/
|
||||
private ProblemReporter problemReporter = new FailFastProblemReporter();
|
||||
|
||||
/**
|
||||
* Populate and return a registry containing all {@link Configuration} bean definitions
|
||||
* to be processed.
|
||||
*
|
||||
* @param includeAbstractBeanDefs whether abstract Configuration bean definitions should
|
||||
* be included in the resulting BeanDefinitionRegistry. Usually false, but called as true
|
||||
* during the enhancement phase.
|
||||
* @see #processConfigBeanDefinitions()
|
||||
*/
|
||||
protected abstract BeanDefinitionRegistry getConfigurationBeanDefinitions(boolean includeAbstractBeanDefs);
|
||||
|
||||
/**
|
||||
* Create and return a new {@link ConfigurationClassParser}, allowing for customization of
|
||||
* type (ASM/JDT/Reflection) as well as providing specialized ClassLoader during
|
||||
* construction.
|
||||
* @see #processConfigBeanDefinitions()
|
||||
*/
|
||||
protected abstract ConfigurationClassParser createConfigurationParser();
|
||||
|
||||
/**
|
||||
* Override the default {@link ProblemReporter}.
|
||||
* @param problemReporter custom problem reporter
|
||||
*/
|
||||
protected final void setProblemReporter(ProblemReporter problemReporter) {
|
||||
this.problemReporter = problemReporter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the currently registered {@link ProblemReporter}.
|
||||
*/
|
||||
protected final ProblemReporter getProblemReporter() {
|
||||
return problemReporter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and validate a {@link ConfigurationModel} based on the registry of
|
||||
* {@link Configuration} classes provided by {@link #getConfigurationBeanDefinitions},
|
||||
* then, based on the content of that model, create and register bean definitions
|
||||
* against a new {@link BeanDefinitionRegistry}, then return the registry.
|
||||
*
|
||||
* @return registry containing one bean definition per {@link Bean} method declared
|
||||
* within the Configuration classes
|
||||
*/
|
||||
protected final BeanDefinitionRegistry processConfigBeanDefinitions() {
|
||||
BeanDefinitionRegistry configBeanDefs = getConfigurationBeanDefinitions(false);
|
||||
|
||||
// return an empty registry immediately if no @Configuration classes were found
|
||||
if(configBeanDefs.getBeanDefinitionCount() == 0)
|
||||
return configBeanDefs;
|
||||
|
||||
// populate a new ConfigurationModel by parsing each @Configuration classes
|
||||
ConfigurationClassParser parser = createConfigurationParser();
|
||||
|
||||
for(String beanName : configBeanDefs.getBeanDefinitionNames()) {
|
||||
BeanDefinition beanDef = configBeanDefs.getBeanDefinition(beanName);
|
||||
String className = beanDef.getBeanClassName();
|
||||
|
||||
parser.parse(className, beanName);
|
||||
}
|
||||
|
||||
ConfigurationModel configModel = parser.getConfigurationModel();
|
||||
|
||||
configModel.validate(problemReporter);
|
||||
|
||||
// read the model and create bean definitions based on its content
|
||||
return new ConfigurationModelBeanDefinitionReader().loadBeanDefinitions(configModel);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import net.sf.cglib.asm.Constants;
|
||||
|
||||
import org.springframework.asm.AnnotationVisitor;
|
||||
import org.springframework.asm.ClassAdapter;
|
||||
import org.springframework.asm.ClassVisitor;
|
||||
import org.springframework.asm.FieldVisitor;
|
||||
import org.springframework.asm.MethodVisitor;
|
||||
|
||||
|
||||
/**
|
||||
* Transforms a class by adding bytecode for a class-level annotation. Checks to ensure that
|
||||
* the desired annotation is not already present before adding. Used by
|
||||
* {@link ConfigurationClassEnhancer} to dynamically add an {@link org.aspectj.lang.Aspect}
|
||||
* annotation to an enhanced Configuration subclass.
|
||||
*
|
||||
* <p>This class was originally adapted from examples the ASM 3.0 documentation.
|
||||
*
|
||||
* @author Chris Beams
|
||||
*/
|
||||
class AddAnnotationAdapter extends ClassAdapter {
|
||||
private String annotationDesc;
|
||||
private boolean isAnnotationPresent;
|
||||
|
||||
/**
|
||||
* Creates a new AddAnnotationAdapter instance.
|
||||
*
|
||||
* @param cv the ClassVisitor delegate
|
||||
* @param annotationDesc name of the annotation to be added (in type descriptor format)
|
||||
*/
|
||||
public AddAnnotationAdapter(ClassVisitor cv, String annotationDesc) {
|
||||
super(cv);
|
||||
this.annotationDesc = annotationDesc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that the version of the resulting class is Java 5 or better.
|
||||
*/
|
||||
@Override
|
||||
public void visit(int version, int access, String name, String signature,
|
||||
String superName, String[] interfaces) {
|
||||
int v = (version & 0xFF) < Constants.V1_5 ? Constants.V1_5 : version;
|
||||
cv.visit(v, access, name, signature, superName, interfaces);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to ensure that the desired annotation is not already present.
|
||||
*/
|
||||
@Override
|
||||
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
|
||||
if (visible && desc.equals(annotationDesc)) {
|
||||
isAnnotationPresent = true;
|
||||
}
|
||||
return cv.visitAnnotation(desc, visible);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitInnerClass(String name, String outerName, String innerName, int access) {
|
||||
addAnnotation();
|
||||
cv.visitInnerClass(name, outerName, innerName, access);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
|
||||
addAnnotation();
|
||||
return cv.visitField(access, name, desc, signature, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
|
||||
addAnnotation();
|
||||
return cv.visitMethod(access, name, desc, signature, exceptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kicks off the process of actually adding the desired annotation.
|
||||
*
|
||||
* @see #addAnnotation()
|
||||
*/
|
||||
@Override
|
||||
public void visitEnd() {
|
||||
addAnnotation();
|
||||
cv.visitEnd();
|
||||
}
|
||||
|
||||
/**
|
||||
* Actually adds the desired annotation.
|
||||
*/
|
||||
private void addAnnotation() {
|
||||
if (!isAnnotationPresent) {
|
||||
AnnotationVisitor av = cv.visitAnnotation(annotationDesc, true);
|
||||
if (av != null) {
|
||||
av.visitEnd();
|
||||
}
|
||||
isAnnotationPresent = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import org.springframework.asm.AnnotationVisitor;
|
||||
|
||||
|
||||
/**
|
||||
* An empty {@link AnnotationVisitor} that delegates to another AnnotationVisitor. This
|
||||
* class can be used as a super class to quickly implement useful annotation adapter
|
||||
* classes, just by overriding the necessary methods. Note that for some reason, ASM
|
||||
* doesn't provide this class (it does provide MethodAdapter and ClassAdapter), thus
|
||||
* we're following the general pattern and adding our own here.
|
||||
*
|
||||
* @author Chris Beams
|
||||
*/
|
||||
class AnnotationAdapter implements AnnotationVisitor {
|
||||
|
||||
private AnnotationVisitor delegate;
|
||||
|
||||
/**
|
||||
* Creates a new AnnotationAdapter instance that will delegate all its calls to
|
||||
* <var>delegate</var>.
|
||||
*
|
||||
* @param delegate In most cases, the delegate will simply be
|
||||
* {@link AsmUtils#ASM_EMPTY_VISITOR}
|
||||
*/
|
||||
public AnnotationAdapter(AnnotationVisitor delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
public void visit(String arg0, Object arg1) {
|
||||
delegate.visit(arg0, arg1);
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitAnnotation(String arg0, String arg1) {
|
||||
return delegate.visitAnnotation(arg0, arg1);
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitArray(String arg0) {
|
||||
return delegate.visitArray(arg0);
|
||||
}
|
||||
|
||||
public void visitEnum(String arg0, String arg1, String arg2) {
|
||||
delegate.visitEnum(arg0, arg1, arg2);
|
||||
}
|
||||
|
||||
public void visitEnd() {
|
||||
delegate.visitEnd();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -45,18 +45,18 @@ import org.springframework.util.ClassUtils;
|
||||
*/
|
||||
public class AnnotationConfigUtils {
|
||||
|
||||
/**
|
||||
* The bean name of the internally managed Configuration annotation processor.
|
||||
*/
|
||||
public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
|
||||
"org.springframework.context.annotation.internalConfigurationAnnotationProcessor";
|
||||
|
||||
/**
|
||||
* The bean name of the internally managed Autowired annotation processor.
|
||||
*/
|
||||
public static final String AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
|
||||
"org.springframework.context.annotation.internalAutowiredAnnotationProcessor";
|
||||
|
||||
/**
|
||||
* The bean name of the internally managed Configuration annotation processor.
|
||||
*/
|
||||
public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
|
||||
"org.springframework.context.annotation.configurationAnnotationProcessor";
|
||||
|
||||
/**
|
||||
* The bean name of the internally managed Required annotation processor.
|
||||
*/
|
||||
@@ -109,18 +109,18 @@ public class AnnotationConfigUtils {
|
||||
|
||||
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(4);
|
||||
|
||||
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
|
||||
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
|
||||
def.setSource(source);
|
||||
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
|
||||
}
|
||||
|
||||
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
|
||||
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
|
||||
def.setSource(source);
|
||||
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
|
||||
}
|
||||
|
||||
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
|
||||
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
|
||||
def.setSource(source);
|
||||
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
|
||||
}
|
||||
|
||||
if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
|
||||
RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
|
||||
def.setSource(source);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
* Copyright 2002-2009 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.
|
||||
@@ -33,13 +33,13 @@ import org.springframework.util.Assert;
|
||||
* @author Mark Fisher
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.5
|
||||
* @see Scope
|
||||
* @see org.springframework.context.annotation.Scope
|
||||
*/
|
||||
public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver {
|
||||
|
||||
private Class<? extends Annotation> scopeAnnotationType = Scope.class;
|
||||
|
||||
private ScopedProxyMode scopedProxyMode;
|
||||
private final ScopedProxyMode defaultProxyMode;
|
||||
|
||||
|
||||
/**
|
||||
@@ -48,16 +48,16 @@ public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver {
|
||||
* @see ScopedProxyMode#NO
|
||||
*/
|
||||
public AnnotationScopeMetadataResolver() {
|
||||
this(ScopedProxyMode.NO);
|
||||
this.defaultProxyMode = ScopedProxyMode.NO;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance of the <code>AnnotationScopeMetadataResolver</code> class.
|
||||
* @param scopedProxyMode the desired scoped-proxy mode
|
||||
* @param defaultProxyMode the desired scoped-proxy mode
|
||||
*/
|
||||
public AnnotationScopeMetadataResolver(ScopedProxyMode scopedProxyMode) {
|
||||
Assert.notNull(scopedProxyMode, "'scopedProxyMode' must not be null");
|
||||
this.scopedProxyMode = scopedProxyMode;
|
||||
public AnnotationScopeMetadataResolver(ScopedProxyMode defaultProxyMode) {
|
||||
Assert.notNull(defaultProxyMode, "'defaultProxyMode' must not be null");
|
||||
this.defaultProxyMode = defaultProxyMode;
|
||||
}
|
||||
|
||||
|
||||
@@ -78,11 +78,16 @@ public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver {
|
||||
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
|
||||
Map<String, Object> attributes =
|
||||
annDef.getMetadata().getAnnotationAttributes(this.scopeAnnotationType.getName());
|
||||
ScopedProxyMode annMode = null;
|
||||
if (attributes != null) {
|
||||
metadata.setScopeName((String) attributes.get("value"));
|
||||
annMode = (ScopedProxyMode) attributes.get("proxyMode");
|
||||
}
|
||||
if (!metadata.getScopeName().equals(BeanDefinition.SCOPE_SINGLETON)) {
|
||||
metadata.setScopedProxyMode(this.scopedProxyMode);
|
||||
if (annMode != null && annMode != ScopedProxyMode.DEFAULT) {
|
||||
metadata.setScopedProxyMode(annMode);
|
||||
}
|
||||
else if (!metadata.getScopeName().equals(BeanDefinition.SCOPE_SINGLETON)) {
|
||||
metadata.setScopedProxyMode(this.defaultProxyMode);
|
||||
}
|
||||
}
|
||||
return metadata;
|
||||
|
||||
@@ -1,229 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
import static org.springframework.util.ClassUtils.*;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.asm.ClassReader;
|
||||
import org.springframework.asm.commons.EmptyVisitor;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Various utility methods commonly used when interacting with ASM, classloading
|
||||
* and creating {@link MutableAnnotation} instances.
|
||||
*
|
||||
* @author Chris Beams
|
||||
*/
|
||||
class AsmUtils {
|
||||
|
||||
public static final EmptyVisitor ASM_EMPTY_VISITOR = new EmptyVisitor();
|
||||
|
||||
private static final Log log = LogFactory.getLog(AsmUtils.class);
|
||||
|
||||
/**
|
||||
* Convert a type descriptor to a classname suitable for classloading with
|
||||
* Class.forName().
|
||||
*
|
||||
* @param typeDescriptor see ASM guide section 2.1.3
|
||||
*/
|
||||
public static String convertAsmTypeDescriptorToClassName(String typeDescriptor) {
|
||||
final String internalName; // See ASM guide section 2.1.2
|
||||
|
||||
if ("V".equals(typeDescriptor))
|
||||
return Void.class.getName();
|
||||
if ("I".equals(typeDescriptor))
|
||||
return Integer.class.getName();
|
||||
if ("Z".equals(typeDescriptor))
|
||||
return Boolean.class.getName();
|
||||
|
||||
// strip the leading array/object/primitive identifier
|
||||
if (typeDescriptor.startsWith("[["))
|
||||
internalName = typeDescriptor.substring(3);
|
||||
else if (typeDescriptor.startsWith("["))
|
||||
internalName = typeDescriptor.substring(2);
|
||||
else
|
||||
internalName = typeDescriptor.substring(1);
|
||||
|
||||
// convert slashes to dots
|
||||
String className = internalName.replace('/', '.');
|
||||
|
||||
// and strip trailing semicolon (if present)
|
||||
if (className.endsWith(";"))
|
||||
className = className.substring(0, internalName.length() - 1);
|
||||
|
||||
return className;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param methodDescriptor see ASM guide section 2.1.4
|
||||
*/
|
||||
public static String getReturnTypeFromAsmMethodDescriptor(String methodDescriptor) {
|
||||
String returnTypeDescriptor = methodDescriptor.substring(methodDescriptor.indexOf(')') + 1);
|
||||
return convertAsmTypeDescriptorToClassName(returnTypeDescriptor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ASM {@link ClassReader} for <var>pathToClass</var>. Appends '.class' to
|
||||
* pathToClass before attempting to load.
|
||||
*
|
||||
* @throws RuntimeException if <var>pathToClass</var>+.class cannot be found on the
|
||||
* classpath
|
||||
* @throws RuntimeException if an IOException occurs when creating the new ClassReader
|
||||
*/
|
||||
public static ClassReader newAsmClassReader(String pathToClass, ClassLoader classLoader) {
|
||||
InputStream is = getClassAsStream(pathToClass, classLoader);
|
||||
return newAsmClassReader(is);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method that creates and returns a new ASM {@link ClassReader} for the
|
||||
* given InputStream <var>is</var>, closing the InputStream after creating the
|
||||
* ClassReader and rethrowing any IOException thrown during ClassReader instantiation as
|
||||
* an unchecked exception. Logs and ignores any IOException thrown when closing the
|
||||
* InputStream.
|
||||
*
|
||||
* @param is InputStream that will be provided to the new ClassReader instance.
|
||||
*/
|
||||
public static ClassReader newAsmClassReader(InputStream is) {
|
||||
try {
|
||||
return new ClassReader(is);
|
||||
} catch (IOException ex) {
|
||||
throw new RuntimeException("An unexpected exception occurred while creating ASM ClassReader: " + ex);
|
||||
} finally {
|
||||
try {
|
||||
is.close();
|
||||
} catch (IOException ex) {
|
||||
log.error("Ignoring exception thrown while closing InputStream", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses the default ClassLoader to load <var>pathToClass</var>. Appends '.class' to
|
||||
* pathToClass before attempting to load.
|
||||
*
|
||||
* @param pathToClass resource path to class, not including .class suffix. e.g.:
|
||||
* com/acme/MyClass
|
||||
*
|
||||
* @return inputStream for <var>pathToClass</var>
|
||||
*
|
||||
* @throws RuntimeException if <var>pathToClass</var> does not exist
|
||||
*/
|
||||
public static InputStream getClassAsStream(String pathToClass, ClassLoader classLoader) {
|
||||
String classFileName = pathToClass + ClassUtils.CLASS_FILE_SUFFIX;
|
||||
|
||||
InputStream is = classLoader.getResourceAsStream(classFileName);
|
||||
|
||||
if (is == null)
|
||||
throw new RuntimeException(
|
||||
new FileNotFoundException("Class file [" + classFileName + "] not found"));
|
||||
|
||||
return is;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the specified class using the default class loader, rethrowing any
|
||||
* {@link ClassNotFoundException} as an unchecked exception.
|
||||
*
|
||||
* @param <T> type of class to be returned
|
||||
* @param fqClassName fully-qualified class name
|
||||
*
|
||||
* @return newly loaded class instance
|
||||
*
|
||||
* @throws IllegalArgumentException if configClassName cannot be loaded.
|
||||
*
|
||||
* @see #loadClass(String)
|
||||
* @see #loadToolingSafeClass(String)
|
||||
* @see ClassUtils#getDefaultClassLoader()
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Class<? extends T> loadRequiredClass(String fqClassName) {
|
||||
try {
|
||||
return (Class<? extends T>) getDefaultClassLoader().loadClass(fqClassName);
|
||||
} catch (ClassNotFoundException ex) {
|
||||
throw new IllegalArgumentException(format(
|
||||
"Class [%s] could not be loaded, check your CLASSPATH.", fqClassName), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the specified class using the default class loader, gracefully handling any
|
||||
* {@link ClassNotFoundException} that may be thrown by issuing a WARN level logging
|
||||
* statement and return null. This functionality is specifically implemented to
|
||||
* accomodate tooling (Spring IDE) concerns, where user-defined types will not be
|
||||
* available to the tooling.
|
||||
* <p>
|
||||
* Because {@link ClassNotFoundException} is compensated for by returning null, callers
|
||||
* must take care to handle the null case appropriately.
|
||||
* <p>
|
||||
* In cases where the WARN logging statement is not desired, use the
|
||||
* {@link #loadClass(String)} method, which returns null but issues no logging
|
||||
* statements.
|
||||
* <p>
|
||||
* This method should only ever return null in the case of a user-defined type be
|
||||
* processed at tooling time. Therefore, tooling may not be able to represent any custom
|
||||
* annotation semantics, but JavaConfig itself will not have any problem loading and
|
||||
* respecting them at actual runtime.
|
||||
*
|
||||
* @param <T> type of class to be returned
|
||||
* @param fqClassName fully-qualified class name
|
||||
*
|
||||
* @return newly loaded class, null if class could not be found.
|
||||
*
|
||||
* @see #loadClass(String)
|
||||
* @see #loadRequiredClass(String)
|
||||
* @see ClassUtils#getDefaultClassLoader()
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Class<? extends T> loadToolingSafeClass(String fqClassName, ClassLoader classLoader) {
|
||||
try {
|
||||
return (Class<? extends T>) classLoader.loadClass(fqClassName);
|
||||
} catch (ClassNotFoundException ex) {
|
||||
log.warn(format("Unable to load class [%s], likely due to tooling-specific restrictions."
|
||||
+ "Attempting to continue, but unexpected errors may occur", fqClassName), ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link MutableAnnotation} for {@code annoType}. JDK dynamic proxies are
|
||||
* used, and the returned proxy implements both {@link MutableAnnotation} and annotation
|
||||
* type {@code A}
|
||||
*
|
||||
* @param <A> annotation type that must be supplied and returned
|
||||
* @param annoType type of annotation to create
|
||||
*/
|
||||
public static <A extends Annotation> A createMutableAnnotation(Class<A> annoType, ClassLoader classLoader) {
|
||||
MutableAnnotationInvocationHandler handler = new MutableAnnotationInvocationHandler(annoType);
|
||||
Class<?>[] interfaces = new Class<?>[] { annoType, MutableAnnotation.class };
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
A mutableAnno = (A) Proxy.newProxyInstance(classLoader, interfaces, handler);
|
||||
return mutableAnno;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowire;
|
||||
|
||||
/**
|
||||
* Indicates that a method produces a bean to be managed by the Spring container. The
|
||||
@@ -60,7 +61,7 @@ import java.lang.annotation.Target;
|
||||
* @see Configuration
|
||||
* @see Lazy
|
||||
* @see Primary
|
||||
* @see Scope
|
||||
* @see org.springframework.context.annotation.Scope
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@@ -74,6 +75,11 @@ public @interface Bean {
|
||||
*/
|
||||
String[] name() default {};
|
||||
|
||||
/**
|
||||
* Are dependencies to be injected via autowiring?
|
||||
*/
|
||||
Autowire autowire() default Autowire.NO;
|
||||
|
||||
/**
|
||||
* The optional name of a method to call on the bean instance during initialization.
|
||||
* Not commonly used, given that the method may be called programmatically directly
|
||||
@@ -82,10 +88,9 @@ public @interface Bean {
|
||||
String initMethod() default "";
|
||||
|
||||
/**
|
||||
* The optional name of a method to call on the bean instance during upon closing
|
||||
* the application context, for example a {@literal close()}
|
||||
* method on a {@literal DataSource}. The method must have no arguments, but may
|
||||
* throw any exception.
|
||||
* The optional name of a method to call on the bean instance during upon closing the
|
||||
* application context, for example a {@literal close()} method on a {@literal DataSource}.
|
||||
* The method must have no arguments, but may throw any exception.
|
||||
* <p>Note: Only invoked on beans whose lifecycle is under the full control of the
|
||||
* factory which is always the case for singletons, but not guaranteed
|
||||
* for any other scope.
|
||||
@@ -93,14 +98,4 @@ public @interface Bean {
|
||||
*/
|
||||
String destroyMethod() default "";
|
||||
|
||||
/**
|
||||
* Beans on which the current bean depends. Any beans specified are guaranteed to be
|
||||
* created by the container before this bean. Used infrequently in cases where a bean
|
||||
* does not explicitly depend on another through properties or constructor arguments,
|
||||
* but rather depends on the side effects of another bean's initialization.
|
||||
* <p>Note: This attribute will not be inherited by child bean definitions,
|
||||
* hence it needs to be specified per concrete bean definition.
|
||||
*/
|
||||
String[] dependsOn() default {};
|
||||
|
||||
}
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import net.sf.cglib.proxy.MethodInterceptor;
|
||||
import net.sf.cglib.proxy.MethodProxy;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Intercepts the invocation of any {@link Bean}-annotated methods in order to ensure proper
|
||||
* handling of bean semantics such as scoping and AOP proxying.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see Bean
|
||||
* @see ConfigurationClassEnhancer
|
||||
*/
|
||||
class BeanMethodInterceptor implements MethodInterceptor {
|
||||
|
||||
private static final Log log = LogFactory.getLog(BeanMethodInterceptor.class);
|
||||
|
||||
private final DefaultListableBeanFactory beanFactory;
|
||||
|
||||
public BeanMethodInterceptor(DefaultListableBeanFactory beanFactory) {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enhances a {@link Bean @Bean} method to check the supplied BeanFactory for the
|
||||
* existence of this bean object.
|
||||
*/
|
||||
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
|
||||
|
||||
// by default the bean name is the name of the @Bean-annotated method
|
||||
String beanName = method.getName();
|
||||
|
||||
// check to see if the user has explicitly set the bean name
|
||||
Bean bean = method.getAnnotation(Bean.class);
|
||||
if(bean != null && bean.name().length > 0)
|
||||
beanName = bean.name()[0];
|
||||
|
||||
// determine whether this bean is a scoped-proxy
|
||||
Scope scope = AnnotationUtils.findAnnotation(method, Scope.class);
|
||||
boolean isScopedProxy = (scope != null && scope.proxyMode() != ScopedProxyMode.NO);
|
||||
String scopedBeanName = ConfigurationModelBeanDefinitionReader.resolveHiddenScopedProxyBeanName(beanName);
|
||||
if (isScopedProxy && beanFactory.isCurrentlyInCreation(scopedBeanName))
|
||||
beanName = scopedBeanName;
|
||||
|
||||
// to handle the case of an inter-bean method reference, we must explicitly check the
|
||||
// container for already cached instances
|
||||
if (factoryContainsBean(beanName)) {
|
||||
// we have an already existing cached instance of this bean -> retrieve it
|
||||
Object cachedBean = beanFactory.getBean(beanName);
|
||||
if (log.isInfoEnabled())
|
||||
log.info(format("Returning cached singleton object [%s] for @Bean method %s.%s",
|
||||
cachedBean, method.getDeclaringClass().getSimpleName(), beanName));
|
||||
|
||||
return cachedBean;
|
||||
}
|
||||
|
||||
// actually create and return the bean
|
||||
return proxy.invokeSuper(obj, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the beanFactory to see whether the bean named <var>beanName</var> already
|
||||
* exists. Accounts for the fact that the requested bean may be "in creation", i.e.:
|
||||
* we're in the middle of servicing the initial request for this bean. From JavaConfig's
|
||||
* perspective, this means that the bean does not actually yet exist, and that it is now
|
||||
* our job to create it for the first time by executing the logic in the corresponding
|
||||
* Bean method.
|
||||
* <p>
|
||||
* Said another way, this check repurposes
|
||||
* {@link ConfigurableBeanFactory#isCurrentlyInCreation(String)} to determine whether
|
||||
* the container is calling this method or the user is calling this method.
|
||||
*
|
||||
* @param beanName name of bean to check for
|
||||
*
|
||||
* @return true if <var>beanName</var> already exists in beanFactory
|
||||
*/
|
||||
private boolean factoryContainsBean(String beanName) {
|
||||
return beanFactory.containsBean(beanName) && !beanFactory.isCurrentlyInCreation(beanName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -197,54 +197,39 @@ public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateCo
|
||||
*/
|
||||
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
|
||||
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
|
||||
for (int i = 0; i < basePackages.length; i++) {
|
||||
Set<BeanDefinition> candidates = findCandidateComponents(basePackages[i]);
|
||||
for (String basePackage : basePackages) {
|
||||
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
|
||||
for (BeanDefinition candidate : candidates) {
|
||||
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
|
||||
if (candidate instanceof AbstractBeanDefinition) {
|
||||
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
|
||||
}
|
||||
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
|
||||
if (candidate instanceof AnnotatedBeanDefinition) {
|
||||
AnnotatedBeanDefinition abd = (AnnotatedBeanDefinition) candidate;
|
||||
if (abd.getMetadata().hasAnnotation(Primary.class.getName())) {
|
||||
abd.setPrimary(true);
|
||||
}
|
||||
if (abd.getMetadata().hasAnnotation(Lazy.class.getName())) {
|
||||
Boolean value = (Boolean) abd.getMetadata().getAnnotationAttributes(Lazy.class.getName()).get("value");
|
||||
abd.setLazyInit(value);
|
||||
}
|
||||
if (abd.getMetadata().hasAnnotation(DependsOn.class.getName())) {
|
||||
String[] value = (String[]) abd.getMetadata().getAnnotationAttributes(DependsOn.class.getName()).get("value");
|
||||
abd.setDependsOn(value);
|
||||
}
|
||||
}
|
||||
if (checkCandidate(beanName, candidate)) {
|
||||
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
|
||||
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
|
||||
definitionHolder = applyScope(definitionHolder, scopeMetadata);
|
||||
beanDefinitions.add(definitionHolder);
|
||||
registerBeanDefinition(definitionHolder, this.registry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
postProcessComponentBeanDefinitions(beanDefinitions);
|
||||
return beanDefinitions;
|
||||
}
|
||||
|
||||
protected void postProcessComponentBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
|
||||
//TODO refactor increment index count as part of naming strategy.
|
||||
Set<BeanDefinitionHolder> factoryBeanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
|
||||
for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitions) {
|
||||
Set<BeanDefinition> candidates = findCandidateFactoryMethods(beanDefinitionHolder);
|
||||
for (BeanDefinition candidate : candidates ) {
|
||||
|
||||
|
||||
BeanDefinitionHolder definitionHolder;
|
||||
if (candidate.getBeanClassName().equals("org.springframework.aop.scope.ScopedProxyFactoryBean")){
|
||||
String scopedFactoryBeanName = "scopedTarget." + candidate.getPropertyValues().getPropertyValue("targetBeanName").getValue();
|
||||
definitionHolder = new BeanDefinitionHolder(candidate, scopedFactoryBeanName);
|
||||
} else {
|
||||
String configurationComponentBeanName = beanDefinitionHolder.getBeanName();
|
||||
String factoryMethodName = candidate.getFactoryMethodName();
|
||||
String beanName = createFactoryBeanName(configurationComponentBeanName, factoryMethodName);
|
||||
definitionHolder = new BeanDefinitionHolder(candidate, beanName);
|
||||
}
|
||||
|
||||
factoryBeanDefinitions.add(definitionHolder);
|
||||
registerBeanDefinition(definitionHolder, this.registry);
|
||||
}
|
||||
}
|
||||
beanDefinitions.addAll(factoryBeanDefinitions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply further settings to the given bean definition,
|
||||
* beyond the contents retrieved from scanning the component class.
|
||||
@@ -325,8 +310,7 @@ public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateCo
|
||||
String scope = scopeMetadata.getScopeName();
|
||||
ScopedProxyMode scopedProxyMode = scopeMetadata.getScopedProxyMode();
|
||||
definitionHolder.getBeanDefinition().setScope(scope);
|
||||
if (BeanDefinition.SCOPE_SINGLETON.equals(scope) || BeanDefinition.SCOPE_PROTOTYPE.equals(scope) ||
|
||||
scopedProxyMode.equals(ScopedProxyMode.NO)) {
|
||||
if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
|
||||
return definitionHolder;
|
||||
}
|
||||
boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
* Copyright 2002-2009 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.
|
||||
@@ -17,33 +17,23 @@
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.aop.scope.ScopedProxyFactoryBean;
|
||||
import org.springframework.beans.factory.BeanDefinitionStoreException;
|
||||
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.BeanDefinitionHolder;
|
||||
import org.springframework.beans.factory.support.AbstractBeanDefinition;
|
||||
import org.springframework.beans.factory.support.AutowireCandidateQualifier;
|
||||
import org.springframework.beans.factory.support.GenericBeanDefinition;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.context.ResourceLoaderAware;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
|
||||
import org.springframework.core.io.support.ResourcePatternResolver;
|
||||
import org.springframework.core.io.support.ResourcePatternUtils;
|
||||
import org.springframework.core.type.MethodMetadata;
|
||||
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
|
||||
import org.springframework.core.type.classreading.MetadataReader;
|
||||
import org.springframework.core.type.classreading.MetadataReaderFactory;
|
||||
@@ -75,13 +65,8 @@ import org.springframework.util.SystemPropertyUtils;
|
||||
*/
|
||||
public class ClassPathScanningCandidateComponentProvider implements ResourceLoaderAware {
|
||||
|
||||
protected static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
|
||||
private static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
|
||||
|
||||
protected static final String QUALIFIER_CLASS_NAME = "org.springframework.beans.factory.annotation.Qualifier";
|
||||
|
||||
protected static final String SCOPE_CLASS_NAME = "org.springframework.context.annotation.Scope";
|
||||
|
||||
protected static final String SCOPEDPROXY_CLASS_NAME = "org.springframework.beans.factory.annotation.ScopedProxy";
|
||||
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
@@ -95,8 +80,6 @@ public class ClassPathScanningCandidateComponentProvider implements ResourceLoad
|
||||
|
||||
private final List<TypeFilter> excludeFilters = new LinkedList<TypeFilter>();
|
||||
|
||||
private int factoryBeanCount = 0;
|
||||
|
||||
|
||||
/**
|
||||
* Create a ClassPathScanningCandidateComponentProvider.
|
||||
@@ -199,33 +182,38 @@ public class ClassPathScanningCandidateComponentProvider implements ResourceLoad
|
||||
Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
|
||||
boolean traceEnabled = logger.isTraceEnabled();
|
||||
boolean debugEnabled = logger.isDebugEnabled();
|
||||
for (int i = 0; i < resources.length; i++) {
|
||||
Resource resource = resources[i];
|
||||
for (Resource resource : resources) {
|
||||
if (traceEnabled) {
|
||||
logger.trace("Scanning " + resource);
|
||||
}
|
||||
if (resource.isReadable()) {
|
||||
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
|
||||
if (isCandidateComponent(metadataReader)) {
|
||||
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
|
||||
sbd.setResource(resource);
|
||||
sbd.setSource(resource);
|
||||
if (isCandidateComponent(sbd)) {
|
||||
if (debugEnabled) {
|
||||
logger.debug("Identified candidate component class: " + resource);
|
||||
try {
|
||||
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
|
||||
if (isCandidateComponent(metadataReader)) {
|
||||
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
|
||||
sbd.setResource(resource);
|
||||
sbd.setSource(resource);
|
||||
if (isCandidateComponent(sbd)) {
|
||||
if (debugEnabled) {
|
||||
logger.debug("Identified candidate component class: " + resource);
|
||||
}
|
||||
candidates.add(sbd);
|
||||
}
|
||||
else {
|
||||
if (debugEnabled) {
|
||||
logger.debug("Ignored because not a concrete top-level class: " + resource);
|
||||
}
|
||||
}
|
||||
candidates.add(sbd);
|
||||
}
|
||||
else {
|
||||
if (debugEnabled) {
|
||||
logger.debug("Ignored because not a concrete top-level class: " + resource);
|
||||
if (traceEnabled) {
|
||||
logger.trace("Ignored because not matching any filter: " + resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (traceEnabled) {
|
||||
logger.trace("Ignored because not matching any filter: " + resource);
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
throw new BeanDefinitionStoreException(
|
||||
"Failed to read candidate component class: " + resource, ex);
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -240,116 +228,6 @@ public class ClassPathScanningCandidateComponentProvider implements ResourceLoad
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
public Set<BeanDefinition> findCandidateFactoryMethods(final BeanDefinitionHolder beanDefinitionHolder) {
|
||||
Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
|
||||
AbstractBeanDefinition containingBeanDef = (AbstractBeanDefinition)beanDefinitionHolder.getBeanDefinition();
|
||||
Resource resource = containingBeanDef.getResource();
|
||||
boolean debugEnabled = logger.isDebugEnabled();
|
||||
boolean traceEnabled = logger.isTraceEnabled();
|
||||
|
||||
try {
|
||||
if (resource.isReadable()) {
|
||||
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
|
||||
Set<MethodMetadata> factoryMethodMetadataSet = metadataReader.getAnnotationMetadata().getAnnotatedMethods("org.springframework.beans.factory.annotation.FactoryMethod");
|
||||
for (MethodMetadata methodMetadata : factoryMethodMetadataSet) {
|
||||
if (isCandidateFactoryMethod(methodMetadata)) {
|
||||
ScannedGenericBeanDefinition factoryBeanDef = new ScannedGenericBeanDefinition(metadataReader);
|
||||
|
||||
if (!methodMetadata.isStatic()) {
|
||||
factoryBeanDef.setFactoryBeanName(beanDefinitionHolder.getBeanName());
|
||||
}
|
||||
factoryBeanDef.setFactoryMethodName(methodMetadata.getMethodName());
|
||||
|
||||
addQualifierToFactoryMethodBeanDefinition(methodMetadata, factoryBeanDef);
|
||||
addScopeToFactoryMethodBeanDefinition(containingBeanDef, methodMetadata, factoryBeanDef);
|
||||
|
||||
factoryBeanDef.setResource(containingBeanDef.getResource());
|
||||
factoryBeanDef.setSource(containingBeanDef.getSource());
|
||||
|
||||
if (debugEnabled) {
|
||||
logger.debug("Identified candidate factory method in class: " + resource);
|
||||
}
|
||||
candidates.add(factoryBeanDef);
|
||||
|
||||
RootBeanDefinition scopedFactoryBeanDef = null;
|
||||
if (methodMetadata.hasAnnotation(SCOPEDPROXY_CLASS_NAME)) {
|
||||
//TODO validate that @ScopedProxy isn't applied to singleton/prototype beans.
|
||||
Map<String, Object> attributes = methodMetadata.getAnnotationAttributes(SCOPEDPROXY_CLASS_NAME);
|
||||
scopedFactoryBeanDef = new RootBeanDefinition(ScopedProxyFactoryBean.class);
|
||||
String t= scopedFactoryBeanDef.getBeanClassName();
|
||||
String targetBeanName = createFactoryBeanName(beanDefinitionHolder.getBeanName(), factoryBeanDef.getFactoryMethodName());
|
||||
scopedFactoryBeanDef.getPropertyValues().addPropertyValue("targetBeanName", targetBeanName);
|
||||
|
||||
//TODO handle cglib options
|
||||
// scopedFactoryBeanDef.getPropertyValues().addPropertyValue("proxyTargetClass", Boolean.FALSE);
|
||||
scopedFactoryBeanDef.setAutowireCandidate(false);
|
||||
scopedFactoryBeanDef.setResource(containingBeanDef.getResource());
|
||||
scopedFactoryBeanDef.setSource(containingBeanDef.getSource());
|
||||
|
||||
candidates.add(scopedFactoryBeanDef);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
else {
|
||||
if (traceEnabled) {
|
||||
logger.trace("Ignored because not matching any filter: " + resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
|
||||
}
|
||||
|
||||
return candidates;
|
||||
}
|
||||
|
||||
|
||||
private void addScopeToFactoryMethodBeanDefinition(
|
||||
AbstractBeanDefinition containingBeanDefinition,
|
||||
MethodMetadata factoryMethodMetadata,
|
||||
ScannedGenericBeanDefinition factoryBeanDefinition) {
|
||||
if (factoryMethodMetadata.hasAnnotation(SCOPE_CLASS_NAME)) {
|
||||
Map<String, Object> attributes = factoryMethodMetadata.getAnnotationAttributes(SCOPE_CLASS_NAME);
|
||||
factoryBeanDefinition.setScope(attributes.get("value").toString());
|
||||
} else {
|
||||
factoryBeanDefinition.setScope(containingBeanDefinition.getScope());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected void addQualifierToFactoryMethodBeanDefinition(MethodMetadata methodMetadata,
|
||||
ScannedGenericBeanDefinition beanDef) {
|
||||
//Add qualifiers to bean definition
|
||||
if (methodMetadata.hasAnnotation(QUALIFIER_CLASS_NAME))
|
||||
{
|
||||
Map<String, Object> attributes = methodMetadata.getAnnotationAttributes(QUALIFIER_CLASS_NAME);
|
||||
beanDef.addQualifier(new AutowireCandidateQualifier(Qualifier.class, attributes.get("value")));
|
||||
}
|
||||
|
||||
if (methodMetadata.hasMetaAnnotation(QUALIFIER_CLASS_NAME))
|
||||
{
|
||||
//Need the attribute that has a qualifier meta-annotation.
|
||||
Set<String> annotationTypes = methodMetadata.getAnnotationTypesWithMetaAnnotation(QUALIFIER_CLASS_NAME);
|
||||
if (annotationTypes.size() == 1)
|
||||
{
|
||||
String annotationType = annotationTypes.iterator().next();
|
||||
Map<String, Object> attributes = methodMetadata.getAnnotationAttributes(annotationType);
|
||||
beanDef.addQualifier(new AutowireCandidateQualifier(annotationType, attributes.get("value")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean isCandidateFactoryMethod(MethodMetadata methodMetadata) {
|
||||
|
||||
//TODO decide if we can support generic wildcard return types, parameter-less method and put in appropriate checks
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
@@ -395,11 +273,4 @@ public class ClassPathScanningCandidateComponentProvider implements ResourceLoad
|
||||
return (beanDefinition.getMetadata().isConcrete() && beanDefinition.getMetadata().isIndependent());
|
||||
}
|
||||
|
||||
|
||||
protected String createFactoryBeanName(String configurationComponentBeanName, String factoryMethodName) {
|
||||
//TODO consider adding hex string and passing in definition object.
|
||||
String beanName = configurationComponentBeanName + "$" + factoryMethodName;
|
||||
return beanName;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
* Copyright 2002-2009 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.
|
||||
@@ -34,6 +34,7 @@ import org.springframework.beans.factory.support.BeanNameGenerator;
|
||||
import org.springframework.beans.factory.xml.BeanDefinitionParser;
|
||||
import org.springframework.beans.factory.xml.ParserContext;
|
||||
import org.springframework.beans.factory.xml.XmlReaderContext;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.core.type.filter.AnnotationTypeFilter;
|
||||
import org.springframework.core.type.filter.AspectJTypeFilter;
|
||||
import org.springframework.core.type.filter.AssignableTypeFilter;
|
||||
@@ -75,8 +76,8 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
|
||||
|
||||
|
||||
public BeanDefinition parse(Element element, ParserContext parserContext) {
|
||||
String[] basePackages =
|
||||
StringUtils.commaDelimitedListToStringArray(element.getAttribute(BASE_PACKAGE_ATTRIBUTE));
|
||||
String[] basePackages = StringUtils.tokenizeToStringArray(element.getAttribute(BASE_PACKAGE_ATTRIBUTE),
|
||||
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
|
||||
|
||||
// Actually scan for bean definitions and register them.
|
||||
ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
|
||||
|
||||
@@ -57,7 +57,7 @@ import org.springframework.stereotype.Component;
|
||||
* @see Value
|
||||
* @see ConfigurationClassPostProcessor;
|
||||
*/
|
||||
@Target( { ElementType.TYPE })
|
||||
@Target({ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -16,44 +16,99 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.beans.BeanMetadataElement;
|
||||
import org.springframework.beans.factory.parsing.Location;
|
||||
import org.springframework.beans.factory.parsing.Problem;
|
||||
import org.springframework.beans.factory.parsing.ProblemReporter;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* Represents a user-defined {@link Configuration @Configuration} class.
|
||||
* Includes a set of {@link Bean} methods, including all such methods defined in the
|
||||
* ancestry of the class, in a 'flattened-out' manner. Note that each {@link BeanMethod}
|
||||
* ancestry of the class, in a 'flattened-out' manner. Note that each {@link ConfigurationClassMethod}
|
||||
* representation contains source information about where it was originally detected
|
||||
* (for the purpose of tooling with Spring IDE).
|
||||
*
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see ConfigurationModel
|
||||
* @see BeanMethod
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
* @see ConfigurationClassMethod
|
||||
* @see ConfigurationClassParser
|
||||
*/
|
||||
final class ConfigurationClass extends ModelClass {
|
||||
final class ConfigurationClass implements BeanMetadataElement {
|
||||
|
||||
private String name;
|
||||
|
||||
private transient Object source;
|
||||
|
||||
private String beanName;
|
||||
|
||||
private int modifiers;
|
||||
private HashSet<Annotation> annotations = new HashSet<Annotation>();
|
||||
private HashSet<BeanMethod> methods = new HashSet<BeanMethod>();
|
||||
|
||||
private Set<Annotation> annotations = new HashSet<Annotation>();
|
||||
|
||||
private Set<ConfigurationClassMethod> methods = new HashSet<ConfigurationClassMethod>();
|
||||
|
||||
private ConfigurationClass declaringClass;
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName == null ? getName() : beanName;
|
||||
|
||||
/**
|
||||
* Returns the fully-qualified name of this class.
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setBeanName(String id) {
|
||||
this.beanName = id;
|
||||
/**
|
||||
* Sets the fully-qualified name of this class.
|
||||
*/
|
||||
public void setName(String className) {
|
||||
this.name = className;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the non-qualified name of this class. Given com.acme.Foo, returns 'Foo'.
|
||||
*/
|
||||
public String getSimpleName() {
|
||||
return name == null ? null : ClassUtils.getShortName(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a resource path-formatted representation of the .java file that declares this
|
||||
* class
|
||||
*/
|
||||
public Object getSource() {
|
||||
return source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the source location for this class. Must be a resource-path formatted string.
|
||||
* @param source resource path to the .java file that declares this class.
|
||||
*/
|
||||
public void setSource(Object source) {
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
public Location getLocation() {
|
||||
if (getName() == null) {
|
||||
throw new IllegalStateException("'name' property is null. Call setName() before calling getLocation()");
|
||||
}
|
||||
return new Location(new ClassPathResource(ClassUtils.convertClassNameToResourcePath(getName())), getSource());
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setBeanName(String beanName) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
|
||||
public int getModifiers() {
|
||||
@@ -76,10 +131,11 @@ final class ConfigurationClass extends ModelClass {
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <A extends Annotation> A getAnnotation(Class<A> annoType) {
|
||||
for (Annotation annotation : annotations)
|
||||
if(annotation.annotationType().equals(annoType))
|
||||
for (Annotation annotation : annotations) {
|
||||
if (annotation.annotationType().equals(annoType)) {
|
||||
return (A) annotation;
|
||||
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -90,19 +146,18 @@ final class ConfigurationClass extends ModelClass {
|
||||
*/
|
||||
public <A extends Annotation> A getRequiredAnnotation(Class<A> annoType) {
|
||||
A anno = getAnnotation(annoType);
|
||||
|
||||
if(anno == null)
|
||||
if (anno == null) {
|
||||
throw new IllegalStateException(
|
||||
format("required annotation %s is not present on %s", annoType.getSimpleName(), this));
|
||||
|
||||
String.format("Required annotation %s is not present on %s", annoType.getSimpleName(), this));
|
||||
}
|
||||
return anno;
|
||||
}
|
||||
|
||||
public Set<BeanMethod> getBeanMethods() {
|
||||
public Set<ConfigurationClassMethod> getBeanMethods() {
|
||||
return methods;
|
||||
}
|
||||
|
||||
public ConfigurationClass addBeanMethod(BeanMethod method) {
|
||||
public ConfigurationClass addMethod(ConfigurationClassMethod method) {
|
||||
method.setDeclaringClass(this);
|
||||
methods.add(method);
|
||||
return this;
|
||||
@@ -117,93 +172,24 @@ final class ConfigurationClass extends ModelClass {
|
||||
}
|
||||
|
||||
public void validate(ProblemReporter problemReporter) {
|
||||
// configuration classes must be annotated with @Configuration
|
||||
if (getAnnotation(Configuration.class) == null)
|
||||
problemReporter.error(new NonAnnotatedConfigurationProblem());
|
||||
|
||||
// a configuration class may not be final (CGLIB limitation)
|
||||
if (Modifier.isFinal(modifiers))
|
||||
problemReporter.error(new FinalConfigurationProblem());
|
||||
|
||||
for (BeanMethod method : methods)
|
||||
method.validate(problemReporter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return format("%s; modifiers=%d; methods=%s", super.toString(), modifiers, methods);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = super.hashCode();
|
||||
result = prime * result
|
||||
+ ((annotations == null) ? 0 : annotations.hashCode());
|
||||
result = prime * result
|
||||
+ ((beanName == null) ? 0 : beanName.hashCode());
|
||||
result = prime * result
|
||||
+ ((declaringClass == null) ? 0 : declaringClass.hashCode());
|
||||
result = prime * result + ((methods == null) ? 0 : methods.hashCode());
|
||||
result = prime * result + modifiers;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (!super.equals(obj))
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
ConfigurationClass other = (ConfigurationClass) obj;
|
||||
if (annotations == null) {
|
||||
if (other.annotations != null)
|
||||
return false;
|
||||
} else if (!annotations.equals(other.annotations))
|
||||
return false;
|
||||
if (beanName == null) {
|
||||
if (other.beanName != null)
|
||||
return false;
|
||||
} else if (!beanName.equals(other.beanName))
|
||||
return false;
|
||||
if (declaringClass == null) {
|
||||
if (other.declaringClass != null)
|
||||
return false;
|
||||
} else if (!declaringClass.equals(other.declaringClass))
|
||||
return false;
|
||||
if (methods == null) {
|
||||
if (other.methods != null)
|
||||
return false;
|
||||
} else if (!methods.equals(other.methods))
|
||||
return false;
|
||||
if (modifiers != other.modifiers)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/** Configuration classes must be annotated with {@link Configuration @Configuration}. */
|
||||
class NonAnnotatedConfigurationProblem extends Problem {
|
||||
|
||||
NonAnnotatedConfigurationProblem() {
|
||||
super(format("%s was specified as a @Configuration class but was not actually annotated " +
|
||||
"with @Configuration. Annotate the class or do not attempt to process it.",
|
||||
getSimpleName()),
|
||||
ConfigurationClass.this.getLocation());
|
||||
if (getAnnotation(Configuration.class) != null) {
|
||||
if (Modifier.isFinal(modifiers)) {
|
||||
problemReporter.error(new FinalConfigurationProblem());
|
||||
}
|
||||
for (ConfigurationClassMethod method : methods) {
|
||||
method.validate(problemReporter);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/** Configuration classes must be non-final to accommodate CGLIB subclassing. */
|
||||
class FinalConfigurationProblem extends Problem {
|
||||
private class FinalConfigurationProblem extends Problem {
|
||||
|
||||
FinalConfigurationProblem() {
|
||||
super(format("@Configuration class [%s] may not be final. Remove the final modifier to continue.",
|
||||
getSimpleName()),
|
||||
ConfigurationClass.this.getLocation());
|
||||
public FinalConfigurationProblem() {
|
||||
super(String.format("@Configuration class [%s] may not be final. Remove the final modifier to continue.",
|
||||
getSimpleName()), ConfigurationClass.this.getLocation());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,24 +16,26 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
|
||||
/**
|
||||
* Interface used when dynamically creating mutable instances of annotations associated
|
||||
* with {@link Configuration} class processing. This functionality is necessary given
|
||||
* that parsing of Configuration classes is done with ASM. Annotation metadata (including
|
||||
* attributes) is parsed from the classfiles, and instances of those annotations are
|
||||
* attributes) is parsed from the class files, and instances of those annotations are
|
||||
* then created using this interface and its associated utilities. The annotation
|
||||
* instances are attached to the {@link ConfigurationModel} objects at runtime, namely
|
||||
* {@link BeanMethod}. This approach is better than the alternative of creating fine-grained
|
||||
* model representations of all annotations and attributes. It is better to simply attach
|
||||
* annotation instances and read them as needed.
|
||||
*
|
||||
* instances are attached to the configuration model objects at runtime, namely
|
||||
* {@link ConfigurationClassMethod}. This approach is better than the alternative of
|
||||
* creating fine-grained model representations of all annotations and attributes.
|
||||
* It is better to simply attach annotation instances and read them as needed.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see MutableAnnotationVisitor
|
||||
* @see MutableAnnotationInvocationHandler
|
||||
* @see AsmUtils#createMutableAnnotation
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
* @see ConfigurationClassAnnotationVisitor
|
||||
* @see ConfigurationClassReaderUtils#createMutableAnnotation
|
||||
*/
|
||||
interface MutableAnnotation {
|
||||
interface ConfigurationClassAnnotation extends Annotation {
|
||||
|
||||
void setAttributeValue(String attribName, Object attribValue);
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.springframework.asm.AnnotationVisitor;
|
||||
import org.springframework.asm.Type;
|
||||
import org.springframework.asm.commons.EmptyVisitor;
|
||||
|
||||
/**
|
||||
* ASM {@link AnnotationVisitor} that populates a given {@link ConfigurationClassAnnotation} instance
|
||||
* with its attributes.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
* @see ConfigurationClassAnnotation
|
||||
* @see ConfigurationClassReaderUtils#createMutableAnnotation
|
||||
*/
|
||||
class ConfigurationClassAnnotationVisitor implements AnnotationVisitor {
|
||||
|
||||
protected final ConfigurationClassAnnotation mutableAnno;
|
||||
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link ConfigurationClassAnnotationVisitor} instance that will populate the the
|
||||
* attributes of the given <var>mutableAnno</var>. Accepts {@link Annotation} instead of
|
||||
* {@link ConfigurationClassAnnotation} to avoid the need for callers to typecast.
|
||||
* @param mutableAnno {@link ConfigurationClassAnnotation} instance to visit and populate
|
||||
* @see ConfigurationClassReaderUtils#createMutableAnnotation
|
||||
*/
|
||||
public ConfigurationClassAnnotationVisitor(ConfigurationClassAnnotation mutableAnno, ClassLoader classLoader) {
|
||||
this.mutableAnno = mutableAnno;
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
public void visit(String attribName, Object attribValue) {
|
||||
Class<?> attribReturnType = mutableAnno.getAttributeType(attribName);
|
||||
|
||||
if (attribReturnType.equals(Class.class)) {
|
||||
// the attribute type is Class -> load it and set it.
|
||||
String fqClassName = ((Type) attribValue).getClassName();
|
||||
Class<?> classVal = ConfigurationClassReaderUtils.loadToolingSafeClass(fqClassName, classLoader);
|
||||
if (classVal == null) {
|
||||
return;
|
||||
}
|
||||
mutableAnno.setAttributeValue(attribName, classVal);
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise, assume the value can be set literally
|
||||
mutableAnno.setAttributeValue(attribName, attribValue);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void visitEnum(String attribName, String enumTypeDescriptor, String strEnumValue) {
|
||||
String enumClassName = ConfigurationClassReaderUtils.convertAsmTypeDescriptorToClassName(enumTypeDescriptor);
|
||||
Class<? extends Enum> enumClass = ConfigurationClassReaderUtils.loadToolingSafeClass(enumClassName, classLoader);
|
||||
if (enumClass == null) {
|
||||
return;
|
||||
}
|
||||
Enum enumValue = Enum.valueOf(enumClass, strEnumValue);
|
||||
mutableAnno.setAttributeValue(attribName, enumValue);
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitAnnotation(String attribName, String attribAnnoTypeDesc) {
|
||||
String annoTypeName = ConfigurationClassReaderUtils.convertAsmTypeDescriptorToClassName(attribAnnoTypeDesc);
|
||||
Class<? extends Annotation> annoType = ConfigurationClassReaderUtils.loadToolingSafeClass(annoTypeName, classLoader);
|
||||
if (annoType == null) {
|
||||
return new EmptyVisitor();
|
||||
}
|
||||
ConfigurationClassAnnotation anno = ConfigurationClassReaderUtils.createMutableAnnotation(annoType, classLoader);
|
||||
try {
|
||||
Field attribute = mutableAnno.getClass().getField(attribName);
|
||||
attribute.set(mutableAnno, anno);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException("Could not reflectively set annotation field", ex);
|
||||
}
|
||||
return new ConfigurationClassAnnotationVisitor(anno, classLoader);
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitArray(final String attribName) {
|
||||
return new MutableAnnotationArrayVisitor(mutableAnno, attribName, classLoader);
|
||||
}
|
||||
|
||||
public void visitEnd() {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ASM {@link AnnotationVisitor} that visits any annotation array values while populating
|
||||
* a new {@link ConfigurationClassAnnotation} instance.
|
||||
*/
|
||||
private static class MutableAnnotationArrayVisitor implements AnnotationVisitor {
|
||||
|
||||
private final List<Object> values = new ArrayList<Object>();
|
||||
|
||||
private final ConfigurationClassAnnotation mutableAnno;
|
||||
|
||||
private final String attribName;
|
||||
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
|
||||
public MutableAnnotationArrayVisitor(ConfigurationClassAnnotation mutableAnno, String attribName, ClassLoader classLoader) {
|
||||
this.mutableAnno = mutableAnno;
|
||||
this.attribName = attribName;
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
|
||||
public void visit(String na, Object value) {
|
||||
values.add(value);
|
||||
}
|
||||
|
||||
public void visitEnum(String s, String s1, String s2) {
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitAnnotation(String na, String annoTypeDesc) {
|
||||
String annoTypeName = ConfigurationClassReaderUtils.convertAsmTypeDescriptorToClassName(annoTypeDesc);
|
||||
Class<? extends Annotation> annoType = ConfigurationClassReaderUtils.loadToolingSafeClass(annoTypeName, classLoader);
|
||||
if (annoType == null) {
|
||||
return new EmptyVisitor();
|
||||
}
|
||||
ConfigurationClassAnnotation anno = ConfigurationClassReaderUtils.createMutableAnnotation(annoType, classLoader);
|
||||
values.add(anno);
|
||||
return new ConfigurationClassAnnotationVisitor(anno, classLoader);
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitArray(String s) {
|
||||
return new EmptyVisitor();
|
||||
}
|
||||
|
||||
public void visitEnd() {
|
||||
Class<?> arrayType = mutableAnno.getAttributeType(attribName);
|
||||
Object[] array = (Object[]) Array.newInstance(arrayType.getComponentType(), 0);
|
||||
mutableAnno.setAttributeValue(attribName, values.toArray(array));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.aop.scope.ScopedProxyUtils;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.BeanDefinitionHolder;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionReader;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.beans.factory.support.GenericBeanDefinition;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.beans.factory.annotation.Autowire;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Reads a given fully-populated configuration model, registering bean definitions
|
||||
* with the given {@link BeanDefinitionRegistry} based on its contents.
|
||||
*
|
||||
* <p>This class was modeled after the {@link BeanDefinitionReader} hierarchy, but does
|
||||
* not implement/extend any of its artifacts as a configuration model is not a {@link Resource}.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
*/
|
||||
class ConfigurationClassBeanDefinitionReader {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(ConfigurationClassBeanDefinitionReader.class);
|
||||
|
||||
private final BeanDefinitionRegistry registry;
|
||||
|
||||
|
||||
public ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry) {
|
||||
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reads {@code configurationModel}, registering bean definitions with {@link #registry}
|
||||
* based on its contents.
|
||||
*/
|
||||
public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
|
||||
for (ConfigurationClass configClass : configurationModel) {
|
||||
loadBeanDefinitionsForConfigurationClass(configClass);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a particular {@link ConfigurationClass}, registering bean definitions for the
|
||||
* class itself, all its {@link Bean} methods
|
||||
*/
|
||||
private void loadBeanDefinitionsForConfigurationClass(ConfigurationClass configClass) {
|
||||
doLoadBeanDefinitionForConfigurationClass(configClass);
|
||||
for (ConfigurationClassMethod method : configClass.getBeanMethods()) {
|
||||
loadBeanDefinitionsForModelMethod(method);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the {@link Configuration} class itself as a bean definition.
|
||||
*/
|
||||
private void doLoadBeanDefinitionForConfigurationClass(ConfigurationClass configClass) {
|
||||
if (configClass.getBeanName() == null) {
|
||||
GenericBeanDefinition configBeanDef = new GenericBeanDefinition();
|
||||
configBeanDef.setBeanClassName(configClass.getName());
|
||||
String configBeanName = BeanDefinitionReaderUtils.registerWithGeneratedName(configBeanDef, registry);
|
||||
configClass.setBeanName(configBeanName);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug(String.format("Registered bean definition for imported @Configuration class %s", configBeanName));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a particular {@link ConfigurationClassMethod}, registering bean definitions with
|
||||
* {@link #registry} based on its contents.
|
||||
*/
|
||||
private void loadBeanDefinitionsForModelMethod(ConfigurationClassMethod method) {
|
||||
RootBeanDefinition beanDef = new ConfigurationClassBeanDefinition();
|
||||
ConfigurationClass configClass = method.getDeclaringClass();
|
||||
beanDef.setFactoryBeanName(configClass.getBeanName());
|
||||
beanDef.setFactoryMethodName(method.getName());
|
||||
beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
|
||||
|
||||
// consider name and any aliases
|
||||
Bean bean = method.getRequiredAnnotation(Bean.class);
|
||||
List<String> names = new ArrayList<String>(Arrays.asList(bean.name()));
|
||||
String beanName = (names.size() > 0) ? names.remove(0) : method.getName();
|
||||
for (String alias : bean.name()) {
|
||||
registry.registerAlias(beanName, alias);
|
||||
}
|
||||
|
||||
// has this already been overriden (i.e.: via XML)?
|
||||
if (registry.containsBeanDefinition(beanName)) {
|
||||
BeanDefinition existingBeanDef = registry.getBeanDefinition(beanName);
|
||||
// is the existing bean definition one that was created by JavaConfig?
|
||||
if (!(existingBeanDef instanceof ConfigurationClassBeanDefinition)) {
|
||||
// no -> then it's an external override, probably XML
|
||||
// overriding is legal, return immediately
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug(String.format("Skipping loading bean definition for %s: a definition for bean " +
|
||||
"'%s' already exists. This is likely due to an override in XML.", method, beanName));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (method.getAnnotation(Primary.class) != null) {
|
||||
beanDef.setPrimary(true);
|
||||
}
|
||||
|
||||
// is this bean to be instantiated lazily?
|
||||
Lazy lazy = method.getAnnotation(Lazy.class);
|
||||
if (lazy != null) {
|
||||
beanDef.setLazyInit(lazy.value());
|
||||
}
|
||||
else {
|
||||
Lazy defaultLazy = configClass.getAnnotation(Lazy.class);
|
||||
if (defaultLazy != null) {
|
||||
beanDef.setLazyInit(defaultLazy.value());
|
||||
}
|
||||
}
|
||||
|
||||
DependsOn dependsOn = method.getAnnotation(DependsOn.class);
|
||||
if (dependsOn != null && dependsOn.value().length > 0) {
|
||||
beanDef.setDependsOn(dependsOn.value());
|
||||
}
|
||||
|
||||
Autowire autowire = bean.autowire();
|
||||
if (autowire.isAutowire()) {
|
||||
beanDef.setAutowireMode(autowire.value());
|
||||
}
|
||||
|
||||
String initMethodName = bean.initMethod();
|
||||
if (StringUtils.hasText(initMethodName)) {
|
||||
beanDef.setInitMethodName(initMethodName);
|
||||
}
|
||||
|
||||
String destroyMethodName = bean.destroyMethod();
|
||||
if (StringUtils.hasText(destroyMethodName)) {
|
||||
beanDef.setDestroyMethodName(destroyMethodName);
|
||||
}
|
||||
|
||||
// consider scoping
|
||||
Scope scope = method.getAnnotation(Scope.class);
|
||||
ScopedProxyMode proxyMode = ScopedProxyMode.NO;
|
||||
if (scope != null) {
|
||||
beanDef.setScope(scope.value());
|
||||
proxyMode = scope.proxyMode();
|
||||
if (proxyMode == ScopedProxyMode.DEFAULT) {
|
||||
proxyMode = ScopedProxyMode.NO;
|
||||
}
|
||||
}
|
||||
|
||||
// replace the original bean definition with the target one, if necessary
|
||||
BeanDefinition beanDefToRegister = beanDef;
|
||||
if (proxyMode != ScopedProxyMode.NO) {
|
||||
BeanDefinitionHolder proxyDef = ScopedProxyUtils.createScopedProxy(
|
||||
new BeanDefinitionHolder(beanDef, beanName), registry, proxyMode == ScopedProxyMode.TARGET_CLASS);
|
||||
beanDefToRegister = proxyDef.getBeanDefinition();
|
||||
}
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug(String.format("Registering bean definition for @Bean method %s.%s()", configClass.getName(), beanName));
|
||||
}
|
||||
|
||||
registry.registerBeanDefinition(beanName, beanDefToRegister);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* {@link RootBeanDefinition} marker subclass used to signify that a bean definition created
|
||||
* by JavaConfig as opposed to any other configuration source. Used in bean overriding cases
|
||||
* where it's necessary to determine whether the bean definition was created externally
|
||||
* (e.g. via XML).
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
private class ConfigurationClassBeanDefinition extends RootBeanDefinition {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,60 +16,59 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
import static org.springframework.context.annotation.AsmUtils.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import net.sf.cglib.core.DefaultGeneratorStrategy;
|
||||
import net.sf.cglib.proxy.Callback;
|
||||
import net.sf.cglib.proxy.CallbackFilter;
|
||||
import net.sf.cglib.proxy.Enhancer;
|
||||
import net.sf.cglib.proxy.MethodInterceptor;
|
||||
import net.sf.cglib.proxy.MethodProxy;
|
||||
import net.sf.cglib.proxy.NoOp;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.asm.ClassAdapter;
|
||||
import org.springframework.asm.ClassReader;
|
||||
import org.springframework.asm.ClassWriter;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
|
||||
import org.springframework.aop.scope.ScopedProxyUtils;
|
||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
/**
|
||||
* Enhances {@link Configuration} classes by generating a CGLIB subclass capable of
|
||||
* interacting with the Spring container to respect bean semantics.
|
||||
*
|
||||
* @see #enhance(String)
|
||||
*
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
* @see #enhance
|
||||
* @see ConfigurationClassPostProcessor
|
||||
*/
|
||||
class ConfigurationClassEnhancer {
|
||||
|
||||
private static final Log log = LogFactory.getLog(ConfigurationClassEnhancer.class);
|
||||
private static final Log logger = LogFactory.getLog(ConfigurationClassEnhancer.class);
|
||||
|
||||
private final List<Callback> callbackInstances = new ArrayList<Callback>();
|
||||
|
||||
private final List<Class<? extends Callback>> callbackTypes = new ArrayList<Class<? extends Callback>>();
|
||||
|
||||
private final ArrayList<Callback> callbackInstances = new ArrayList<Callback>();
|
||||
private final ArrayList<Class<? extends Callback>> callbackTypes = new ArrayList<Class<? extends Callback>>();
|
||||
private final CallbackFilter callbackFilter;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link ConfigurationClassEnhancer} instance.
|
||||
*/
|
||||
public ConfigurationClassEnhancer(DefaultListableBeanFactory beanFactory) {
|
||||
Assert.notNull(beanFactory, "beanFactory must be non-null");
|
||||
public ConfigurationClassEnhancer(ConfigurableBeanFactory beanFactory) {
|
||||
Assert.notNull(beanFactory, "BeanFactory must not be null");
|
||||
|
||||
callbackInstances.add(new BeanMethodInterceptor(beanFactory));
|
||||
callbackInstances.add(NoOp.INSTANCE);
|
||||
|
||||
for (Callback callback : callbackInstances)
|
||||
for (Callback callback : callbackInstances) {
|
||||
callbackTypes.add(callback.getClass());
|
||||
}
|
||||
|
||||
// set up the callback filter to return the index of the BeanMethodInterceptor when
|
||||
// Set up the callback filter to return the index of the BeanMethodInterceptor when
|
||||
// handling a @Bean-annotated method; otherwise, return index of the NoOp callback.
|
||||
callbackFilter = new CallbackFilter() {
|
||||
public int accept(Method candidateMethod) {
|
||||
@@ -82,24 +81,18 @@ class ConfigurationClassEnhancer {
|
||||
/**
|
||||
* Loads the specified class and generates a CGLIB subclass of it equipped with
|
||||
* container-aware callbacks capable of respecting scoping and other bean semantics.
|
||||
*
|
||||
* @return fully-qualified name of the enhanced subclass
|
||||
*/
|
||||
public String enhance(String configClassName) {
|
||||
if (log.isInfoEnabled())
|
||||
log.info("Enhancing " + configClassName);
|
||||
|
||||
Class<?> superclass = loadRequiredClass(configClassName);
|
||||
|
||||
Class<?> subclass = createClass(newEnhancer(superclass), superclass);
|
||||
|
||||
subclass = nestOneClassDeeperIfAspect(superclass, subclass);
|
||||
|
||||
if (log.isInfoEnabled())
|
||||
log.info(format("Successfully enhanced %s; enhanced class name is: %s",
|
||||
configClassName, subclass.getName()));
|
||||
|
||||
return subclass.getName();
|
||||
public Class enhance(Class configClass) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Enhancing " + configClass.getName());
|
||||
}
|
||||
Class<?> enhancedClass = createClass(newEnhancer(configClass));
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info(String.format("Successfully enhanced %s; enhanced class name is: %s",
|
||||
configClass.getName(), enhancedClass.getName()));
|
||||
}
|
||||
return enhancedClass;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -116,7 +109,7 @@ class ConfigurationClassEnhancer {
|
||||
enhancer.setSuperclass(superclass);
|
||||
enhancer.setUseFactory(false);
|
||||
enhancer.setCallbackFilter(callbackFilter);
|
||||
enhancer.setCallbackTypes(callbackTypes.toArray(new Class<?>[] {}));
|
||||
enhancer.setCallbackTypes(callbackTypes.toArray(new Class[callbackTypes.size()]));
|
||||
|
||||
return enhancer;
|
||||
}
|
||||
@@ -125,53 +118,86 @@ class ConfigurationClassEnhancer {
|
||||
* Uses enhancer to generate a subclass of superclass, ensuring that
|
||||
* {@link #callbackInstances} are registered for the new subclass.
|
||||
*/
|
||||
private Class<?> createClass(Enhancer enhancer, Class<?> superclass) {
|
||||
private Class<?> createClass(Enhancer enhancer) {
|
||||
Class<?> subclass = enhancer.createClass();
|
||||
|
||||
Enhancer.registerCallbacks(subclass, callbackInstances.toArray(new Callback[] {}));
|
||||
|
||||
Enhancer.registerCallbacks(subclass, callbackInstances.toArray(new Callback[callbackInstances.size()]));
|
||||
return subclass;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Works around a constraint imposed by the AspectJ 5 annotation-style programming
|
||||
* model. See comments inline for detail.
|
||||
*
|
||||
* @return original subclass instance unless superclass is annnotated with @Aspect, in
|
||||
* which case a subclass of the subclass is returned
|
||||
* Intercepts the invocation of any {@link Bean}-annotated methods in order to ensure proper
|
||||
* handling of bean semantics such as scoping and AOP proxying.
|
||||
* @author Chris Beams
|
||||
* @see Bean
|
||||
* @see ConfigurationClassEnhancer
|
||||
*/
|
||||
private Class<?> nestOneClassDeeperIfAspect(Class<?> superclass, Class<?> origSubclass) {
|
||||
boolean superclassIsAnAspect = false;
|
||||
private static class BeanMethodInterceptor implements MethodInterceptor {
|
||||
|
||||
// check for @Aspect by name rather than by class literal to avoid
|
||||
// requiring AspectJ as a runtime dependency.
|
||||
for (Annotation anno : superclass.getAnnotations())
|
||||
if (anno.annotationType().getName().equals("org.aspectj.lang.annotation.Aspect"))
|
||||
superclassIsAnAspect = true;
|
||||
private static final Log logger = LogFactory.getLog(BeanMethodInterceptor.class);
|
||||
|
||||
if (!superclassIsAnAspect)
|
||||
return origSubclass;
|
||||
private final ConfigurableBeanFactory beanFactory;
|
||||
|
||||
// the superclass is annotated with AspectJ's @Aspect.
|
||||
// this means that we must create a subclass of the subclass
|
||||
// in order to avoid some guard logic in Spring core that disallows
|
||||
// extending a concrete aspect class.
|
||||
Enhancer enhancer = newEnhancer(origSubclass);
|
||||
enhancer.setStrategy(new DefaultGeneratorStrategy() {
|
||||
@Override
|
||||
protected byte[] transform(byte[] b) throws Exception {
|
||||
ClassWriter writer = new ClassWriter(false);
|
||||
ClassAdapter adapter = new AddAnnotationAdapter(writer, "Lorg/aspectj/lang/annotation/Aspect;");
|
||||
ClassReader reader = new ClassReader(b);
|
||||
reader.accept(adapter, false);
|
||||
return writer.toByteArray();
|
||||
public BeanMethodInterceptor(ConfigurableBeanFactory beanFactory) {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Enhance a {@link Bean @Bean} method to check the supplied BeanFactory for the
|
||||
* existence of this bean object.
|
||||
*/
|
||||
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
|
||||
// by default the bean name is the name of the @Bean-annotated method
|
||||
String beanName = method.getName();
|
||||
|
||||
// check to see if the user has explicitly set the bean name
|
||||
Bean bean = method.getAnnotation(Bean.class);
|
||||
if(bean != null && bean.name().length > 0) {
|
||||
beanName = bean.name()[0];
|
||||
}
|
||||
});
|
||||
|
||||
// create a subclass of the original subclass
|
||||
Class<?> newSubclass = createClass(enhancer, origSubclass);
|
||||
// determine whether this bean is a scoped-proxy
|
||||
Scope scope = AnnotationUtils.findAnnotation(method, Scope.class);
|
||||
if (scope != null && scope.proxyMode() != ScopedProxyMode.NO) {
|
||||
String scopedBeanName = ScopedProxyUtils.getTargetBeanName(beanName);
|
||||
if (beanFactory.isCurrentlyInCreation(scopedBeanName)) {
|
||||
beanName = scopedBeanName;
|
||||
}
|
||||
}
|
||||
|
||||
// to handle the case of an inter-bean method reference, we must explicitly check the
|
||||
// container for already cached instances
|
||||
if (factoryContainsBean(beanName)) {
|
||||
// we have an already existing cached instance of this bean -> retrieve it
|
||||
Object cachedBean = beanFactory.getBean(beanName);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug(String.format("Returning cached object [%s] for @Bean method %s.%s",
|
||||
cachedBean, method.getDeclaringClass().getSimpleName(), beanName));
|
||||
}
|
||||
return cachedBean;
|
||||
}
|
||||
|
||||
// actually create and return the bean
|
||||
return proxy.invokeSuper(obj, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the beanFactory to see whether the bean named <var>beanName</var> already
|
||||
* exists. Accounts for the fact that the requested bean may be "in creation", i.e.:
|
||||
* we're in the middle of servicing the initial request for this bean. From JavaConfig's
|
||||
* perspective, this means that the bean does not actually yet exist, and that it is now
|
||||
* our job to create it for the first time by executing the logic in the corresponding
|
||||
* Bean method.
|
||||
* <p>Said another way, this check repurposes
|
||||
* {@link ConfigurableBeanFactory#isCurrentlyInCreation(String)} to determine whether
|
||||
* the container is calling this method or the user is calling this method.
|
||||
* @param beanName name of bean to check for
|
||||
* @return true if <var>beanName</var> already exists in the factory
|
||||
*/
|
||||
private boolean factoryContainsBean(String beanName) {
|
||||
return beanFactory.containsBean(beanName) && !beanFactory.isCurrentlyInCreation(beanName);
|
||||
}
|
||||
|
||||
return newSubclass;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,9 +16,6 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
import static org.springframework.context.annotation.StandardScopes.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
@@ -28,34 +25,42 @@ import org.springframework.beans.factory.parsing.Location;
|
||||
import org.springframework.beans.factory.parsing.Problem;
|
||||
import org.springframework.beans.factory.parsing.ProblemReporter;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
/**
|
||||
* Represents a {@link Configuration} class method marked with the {@link Bean} annotation.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
* @see ConfigurationClass
|
||||
* @see ConfigurationModel
|
||||
* @see ConfigurationClassParser
|
||||
* @see ConfigurationModelBeanDefinitionReader
|
||||
* @see ConfigurationClassBeanDefinitionReader
|
||||
*/
|
||||
final class BeanMethod implements BeanMetadataElement {
|
||||
final class ConfigurationClassMethod implements BeanMetadataElement {
|
||||
|
||||
private final String name;
|
||||
|
||||
private final int modifiers;
|
||||
private final ModelClass returnType;
|
||||
|
||||
private final ReturnType returnType;
|
||||
|
||||
private final ArrayList<Annotation> annotations = new ArrayList<Annotation>();
|
||||
|
||||
private transient ConfigurationClass declaringClass;
|
||||
|
||||
private transient Object source;
|
||||
|
||||
public BeanMethod(String name, int modifiers, ModelClass returnType, Annotation... annotations) {
|
||||
|
||||
public ConfigurationClassMethod(String name, int modifiers, ReturnType returnType, Annotation... annotations) {
|
||||
Assert.hasText(name);
|
||||
this.name = name;
|
||||
|
||||
Assert.notNull(annotations);
|
||||
for (Annotation annotation : annotations)
|
||||
for (Annotation annotation : annotations) {
|
||||
this.annotations.add(annotation);
|
||||
}
|
||||
|
||||
Assert.isTrue(modifiers >= 0, "modifiers must be non-negative: " + modifiers);
|
||||
this.modifiers = modifiers;
|
||||
@@ -68,7 +73,7 @@ final class BeanMethod implements BeanMetadataElement {
|
||||
return name;
|
||||
}
|
||||
|
||||
public ModelClass getReturnType() {
|
||||
public ReturnType getReturnType() {
|
||||
return returnType;
|
||||
}
|
||||
|
||||
@@ -100,18 +105,17 @@ final class BeanMethod implements BeanMetadataElement {
|
||||
*/
|
||||
public <T extends Annotation> T getRequiredAnnotation(Class<T> annoType) {
|
||||
T anno = getAnnotation(annoType);
|
||||
|
||||
if(anno == null)
|
||||
if (anno == null) {
|
||||
throw new IllegalStateException(
|
||||
format("required annotation %s is not present on %s", annoType.getSimpleName(), this));
|
||||
|
||||
String.format("required annotation %s is not present on %s", annoType.getSimpleName(), this));
|
||||
}
|
||||
return anno;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up a bi-directional relationship between this method and its declaring class.
|
||||
*
|
||||
* @see ConfigurationClass#addBeanMethod(BeanMethod)
|
||||
* @see ConfigurationClass#addMethod(ConfigurationClassMethod)
|
||||
*/
|
||||
public void setDeclaringClass(ConfigurationClass declaringClass) {
|
||||
this.declaringClass = declaringClass;
|
||||
@@ -130,97 +134,118 @@ final class BeanMethod implements BeanMetadataElement {
|
||||
}
|
||||
|
||||
public Location getLocation() {
|
||||
if (declaringClass == null)
|
||||
if (declaringClass == null) {
|
||||
throw new IllegalStateException(
|
||||
"declaringClass property is null. Call setDeclaringClass() before calling getLocation()");
|
||||
}
|
||||
return new Location(declaringClass.getLocation().getResource(), getSource());
|
||||
}
|
||||
|
||||
public void validate(ProblemReporter problemReporter) {
|
||||
|
||||
if (Modifier.isPrivate(getModifiers()))
|
||||
if (Modifier.isPrivate(getModifiers())) {
|
||||
problemReporter.error(new PrivateMethodError());
|
||||
|
||||
if (Modifier.isFinal(getModifiers()))
|
||||
}
|
||||
if (Modifier.isFinal(getModifiers())) {
|
||||
problemReporter.error(new FinalMethodError());
|
||||
|
||||
Scope scope = this.getAnnotation(Scope.class);
|
||||
if(scope != null
|
||||
&& scope.proxyMode() != ScopedProxyMode.NO
|
||||
&& (scope.value().equals(SINGLETON) || scope.value().equals(PROTOTYPE)))
|
||||
problemReporter.error(new InvalidScopedProxyDeclarationError(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String returnTypeName = returnType == null ? "<unknown>" : returnType.getSimpleName();
|
||||
return format("%s: name=%s; returnType=%s; modifiers=%d",
|
||||
getClass().getSimpleName(), name, returnTypeName, modifiers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((annotations == null) ? 0 : annotations.hashCode());
|
||||
result = prime * result + modifiers;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
result = prime * result + ((returnType == null) ? 0 : returnType.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
BeanMethod other = (BeanMethod) obj;
|
||||
if (annotations == null) {
|
||||
if (other.annotations != null)
|
||||
return false;
|
||||
} else if (!annotations.equals(other.annotations))
|
||||
return false;
|
||||
if (modifiers != other.modifiers)
|
||||
return false;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
if (returnType == null) {
|
||||
if (other.returnType != null)
|
||||
return false;
|
||||
} else if (!returnType.equals(other.returnType))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** {@link Bean} methods must be non-private in order to accommodate CGLIB. */
|
||||
class PrivateMethodError extends Problem {
|
||||
PrivateMethodError() {
|
||||
super(format("Method '%s' may not be private; increase the method's visibility to continue", getName()),
|
||||
BeanMethod.this.getLocation());
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link Bean} methods must be non-final in order to accommodate CGLIB. */
|
||||
class FinalMethodError extends Problem {
|
||||
FinalMethodError() {
|
||||
super(format("Method '%s' may not be final; remove the final modifier to continue", getName()),
|
||||
BeanMethod.this.getLocation());
|
||||
|
||||
static class ReturnType implements BeanMetadataElement {
|
||||
|
||||
private String name;
|
||||
|
||||
private boolean isInterface;
|
||||
|
||||
private transient Object source;
|
||||
|
||||
|
||||
public ReturnType(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fully-qualified name of this class.
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the fully-qualified name of this class.
|
||||
*/
|
||||
public void setName(String className) {
|
||||
this.name = className;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the non-qualified name of this class. Given com.acme.Foo, returns 'Foo'.
|
||||
*/
|
||||
public String getSimpleName() {
|
||||
return name == null ? null : ClassUtils.getShortName(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the class represented by this ModelClass instance is an interface.
|
||||
*/
|
||||
public boolean isInterface() {
|
||||
return isInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Signifies that this class is (true) or is not (false) an interface.
|
||||
*/
|
||||
public void setInterface(boolean isInterface) {
|
||||
this.isInterface = isInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a resource path-formatted representation of the .java file that declares this
|
||||
* class
|
||||
*/
|
||||
public Object getSource() {
|
||||
return source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the source location for this class. Must be a resource-path formatted string.
|
||||
*
|
||||
* @param source resource path to the .java file that declares this class.
|
||||
*/
|
||||
public void setSource(Object source) {
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
public Location getLocation() {
|
||||
if (getName() == null) {
|
||||
throw new IllegalStateException("'name' property is null. Call setName() before calling getLocation()");
|
||||
}
|
||||
return new Location(new ClassPathResource(ClassUtils.convertClassNameToResourcePath(getName())), getSource());
|
||||
}
|
||||
}
|
||||
|
||||
class InvalidScopedProxyDeclarationError extends Problem {
|
||||
InvalidScopedProxyDeclarationError(BeanMethod method) {
|
||||
super(format("Method %s contains an invalid annotation declaration: scoped proxies "
|
||||
+ "cannot be created for singleton/prototype beans", method.getName()),
|
||||
BeanMethod.this.getLocation());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link Bean} methods must be non-private in order to accommodate CGLIB.
|
||||
*/
|
||||
private class PrivateMethodError extends Problem {
|
||||
|
||||
public PrivateMethodError() {
|
||||
super(String.format("Method '%s' must not be private; increase the method's visibility to continue",
|
||||
getName()), ConfigurationClassMethod.this.getLocation());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link Bean} methods must be non-final in order to accommodate CGLIB.
|
||||
*/
|
||||
private class FinalMethodError extends Problem {
|
||||
|
||||
public FinalMethodError() {
|
||||
super(String.format("Method '%s' must not be final; remove the final modifier to continue",
|
||||
getName()), ConfigurationClassMethod.this.getLocation());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static org.springframework.context.annotation.AsmUtils.*;
|
||||
import static org.springframework.util.ClassUtils.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.springframework.asm.AnnotationVisitor;
|
||||
import org.springframework.asm.ClassAdapter;
|
||||
import org.springframework.asm.Label;
|
||||
import org.springframework.asm.MethodAdapter;
|
||||
import org.springframework.asm.MethodVisitor;
|
||||
import org.springframework.asm.Opcodes;
|
||||
|
||||
|
||||
/**
|
||||
* ASM {@link MethodVisitor} that visits a single method declared in a given
|
||||
* {@link Configuration} class. Determines whether the method is a {@link Bean}
|
||||
* method and if so, adds it to the {@link ConfigurationClass}.
|
||||
*
|
||||
* @author Chris Beams
|
||||
*/
|
||||
class ConfigurationClassMethodVisitor extends MethodAdapter {
|
||||
|
||||
private final ConfigurationClass configClass;
|
||||
private final String methodName;
|
||||
private final int modifiers;
|
||||
private final ModelClass returnType;
|
||||
private final ArrayList<Annotation> annotations = new ArrayList<Annotation>();
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
private int lineNumber;
|
||||
|
||||
/**
|
||||
* Creates a new {@link ConfigurationClassMethodVisitor} instance.
|
||||
*
|
||||
* @param configClass model object to which this method will be added
|
||||
* @param methodName name of the method declared in the {@link Configuration} class
|
||||
* @param methodDescriptor ASM representation of the method signature
|
||||
* @param modifiers modifiers for this method
|
||||
*/
|
||||
public ConfigurationClassMethodVisitor(ConfigurationClass configClass, String methodName,
|
||||
String methodDescriptor, int modifiers, ClassLoader classLoader) {
|
||||
super(ASM_EMPTY_VISITOR);
|
||||
|
||||
this.configClass = configClass;
|
||||
this.methodName = methodName;
|
||||
this.classLoader = classLoader;
|
||||
this.modifiers = modifiers;
|
||||
this.returnType = initReturnTypeFromMethodDescriptor(methodDescriptor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a single annotation on this method. Will be called once for each annotation
|
||||
* present (regardless of its RetentionPolicy).
|
||||
*/
|
||||
@Override
|
||||
public AnnotationVisitor visitAnnotation(String annoTypeDesc, boolean visible) {
|
||||
String annoClassName = convertAsmTypeDescriptorToClassName(annoTypeDesc);
|
||||
|
||||
Class<? extends Annotation> annoClass = loadToolingSafeClass(annoClassName, classLoader);
|
||||
|
||||
if (annoClass == null)
|
||||
return super.visitAnnotation(annoTypeDesc, visible);
|
||||
|
||||
Annotation annotation = createMutableAnnotation(annoClass, classLoader);
|
||||
|
||||
annotations.add(annotation);
|
||||
|
||||
return new MutableAnnotationVisitor(annotation, classLoader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides the line number of this method within its declaring class. In reality, this
|
||||
* number is always inaccurate - <var>lineNo</var> represents the line number of the
|
||||
* first instruction in this method. Method declaration line numbers are not in any way
|
||||
* tracked in the bytecode. Any tooling or output that reads this value will have to
|
||||
* compensate and estimate where the actual method declaration is.
|
||||
*/
|
||||
@Override
|
||||
public void visitLineNumber(int lineNo, Label start) {
|
||||
this.lineNumber = lineNo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses through all {@link #annotations} on this method in order to determine whether
|
||||
* it is a {@link Bean} method and if so adds it to the enclosing {@link #configClass}.
|
||||
*/
|
||||
@Override
|
||||
public void visitEnd() {
|
||||
for (Annotation anno : annotations) {
|
||||
if (Bean.class.equals(anno.annotationType())) {
|
||||
// this method is annotated with @Bean -> add it to the ConfigurationClass model
|
||||
Annotation[] annoArray = annotations.toArray(new Annotation[] {});
|
||||
BeanMethod method = new BeanMethod(methodName, modifiers, returnType, annoArray);
|
||||
method.setSource(lineNumber);
|
||||
configClass.addBeanMethod(method);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines return type from ASM <var>methodDescriptor</var> and determines whether
|
||||
* that type is an interface.
|
||||
*/
|
||||
private ModelClass initReturnTypeFromMethodDescriptor(String methodDescriptor) {
|
||||
final ModelClass returnType = new ModelClass(getReturnTypeFromAsmMethodDescriptor(methodDescriptor));
|
||||
|
||||
// detect whether the return type is an interface
|
||||
newAsmClassReader(convertClassNameToResourcePath(returnType.getName()), classLoader).accept(
|
||||
new ClassAdapter(ASM_EMPTY_VISITOR) {
|
||||
@Override
|
||||
public void visit(int arg0, int arg1, String arg2, String arg3, String arg4, String[] arg5) {
|
||||
returnType.setInterface((arg1 & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE);
|
||||
}
|
||||
}, false);
|
||||
|
||||
return returnType;
|
||||
}
|
||||
}
|
||||
@@ -16,75 +16,79 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import static org.springframework.context.annotation.AsmUtils.*;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.Stack;
|
||||
|
||||
import org.springframework.asm.ClassReader;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.parsing.ProblemReporter;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Parses a {@link Configuration} class definition, populating a {@link ConfigurationModel}.
|
||||
* Parses a {@link Configuration} class definition, populating a configuration model.
|
||||
* This ASM-based implementation avoids reflection and eager classloading in order to
|
||||
* interoperate effectively with tooling (Spring IDE) and OSGi environments.
|
||||
* <p>
|
||||
* This class helps separate the concern of parsing the structure of a Configuration class
|
||||
*
|
||||
* <p>This class helps separate the concern of parsing the structure of a Configuration class
|
||||
* from the concern of registering {@link BeanDefinition} objects based on the content of
|
||||
* that model.
|
||||
*
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see ConfigurationModel
|
||||
* @see ConfigurationModelBeanDefinitionReader
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
* @see ConfigurationClassBeanDefinitionReader
|
||||
*/
|
||||
class ConfigurationClassParser {
|
||||
|
||||
/**
|
||||
* Model to be populated during calls to {@link #parse(Object, String)}
|
||||
*/
|
||||
private final ConfigurationModel model;
|
||||
private final Set<ConfigurationClass> model;
|
||||
|
||||
private final ProblemReporter problemReporter;
|
||||
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new {@link ConfigurationClassParser} instance that will be used to populate a
|
||||
* {@link ConfigurationModel}.
|
||||
*
|
||||
* Create a new {@link ConfigurationClassParser} instance that will be used to populate a
|
||||
* configuration model.
|
||||
* @param model model to be populated by each successive call to {@link #parse}
|
||||
* @see #getConfigurationModel()
|
||||
*/
|
||||
public ConfigurationClassParser(ProblemReporter problemReporter, ClassLoader classLoader) {
|
||||
this.model = new ConfigurationModel();
|
||||
this.model = new LinkedHashSet<ConfigurationClass>();
|
||||
this.problemReporter = problemReporter;
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parse the {@link Configuration @Configuration} class encapsulated by
|
||||
* <var>configurationSource</var>.
|
||||
*
|
||||
* @param configurationSource reader for Configuration class being parsed
|
||||
* @param configurationId may be null, but if populated represents the bean id (assumes
|
||||
* that this configuration class was configured via XML)
|
||||
* Parse the specified {@link Configuration @Configuration} class.
|
||||
* @param className the name of the class to parse
|
||||
* @param beanName may be null, but if populated represents the bean id
|
||||
* (assumes that this configuration class was configured via XML)
|
||||
*/
|
||||
public void parse(String className, String configurationId) {
|
||||
|
||||
public void parse(String className, String beanName) {
|
||||
String resourcePath = ClassUtils.convertClassNameToResourcePath(className);
|
||||
|
||||
ClassReader configClassReader = newAsmClassReader(getClassAsStream(resourcePath, classLoader));
|
||||
|
||||
ClassReader configClassReader = ConfigurationClassReaderUtils.newAsmClassReader(ConfigurationClassReaderUtils.getClassAsStream(resourcePath, classLoader));
|
||||
ConfigurationClass configClass = new ConfigurationClass();
|
||||
configClass.setBeanName(configurationId);
|
||||
|
||||
configClass.setBeanName(beanName);
|
||||
configClassReader.accept(new ConfigurationClassVisitor(configClass, model, problemReporter, classLoader), false);
|
||||
model.add(configClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current {@link ConfigurationModel}, to be called after {@link #parse}.
|
||||
* Recurse through the model validating each {@link ConfigurationClass}.
|
||||
* @param problemReporter {@link ProblemReporter} against which any validation errors
|
||||
* will be registered
|
||||
* @see ConfigurationClass#validate
|
||||
*/
|
||||
public ConfigurationModel getConfigurationModel() {
|
||||
return model;
|
||||
public void validate() {
|
||||
for (ConfigurationClass configClass : this.model) {
|
||||
configClass.validate(this.problemReporter);
|
||||
}
|
||||
}
|
||||
|
||||
public Set<ConfigurationClass> getModel() {
|
||||
return this.model;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,28 +16,31 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
|
||||
import org.springframework.beans.factory.BeanClassLoaderAware;
|
||||
import org.springframework.beans.factory.BeanDefinitionStoreException;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.BeanDefinitionHolder;
|
||||
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.beans.factory.parsing.FailFastProblemReporter;
|
||||
import org.springframework.beans.factory.parsing.ProblemReporter;
|
||||
import org.springframework.beans.factory.support.AbstractBeanDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.core.Conventions;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.core.type.ClassMetadata;
|
||||
import org.springframework.core.type.classreading.MetadataReader;
|
||||
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* {@link BeanFactoryPostProcessor} used for bootstrapping processing of
|
||||
@@ -53,129 +56,134 @@ import org.springframework.util.StringUtils;
|
||||
* executes.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
*/
|
||||
public class ConfigurationClassPostProcessor extends AbstractConfigurationClassProcessor
|
||||
implements Ordered, BeanFactoryPostProcessor {
|
||||
public class ConfigurationClassPostProcessor implements BeanFactoryPostProcessor, BeanClassLoaderAware {
|
||||
|
||||
public static final String CONFIGURATION_CLASS_ATTRIBUTE =
|
||||
Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");
|
||||
|
||||
/** Whether the CGLIB2 library is present on the classpath */
|
||||
private static final boolean cglibAvailable = ClassUtils.isPresent(
|
||||
"net.sf.cglib.proxy.Enhancer", ConfigurationClassPostProcessor.class.getClassLoader());
|
||||
|
||||
|
||||
private static final Log logger = LogFactory.getLog(ConfigurationClassPostProcessor.class);
|
||||
|
||||
/**
|
||||
* A well-known class in the CGLIB API used when testing to see if CGLIB
|
||||
* is present on the classpath. Package-private visibility allows for
|
||||
* manipulation by tests.
|
||||
* @see #assertCglibIsPresent(BeanDefinitionRegistry)
|
||||
* Used to register any problems detected with {@link Configuration} or {@link Bean}
|
||||
* declarations. For instance, a Bean method marked as {@literal final} is illegal
|
||||
* and would be reported as a problem. Defaults to {@link FailFastProblemReporter},
|
||||
* but is overridable with {@link #setProblemReporter}
|
||||
*/
|
||||
static String CGLIB_TEST_CLASS = "net.sf.cglib.proxy.Callback";
|
||||
private ProblemReporter problemReporter = new FailFastProblemReporter();
|
||||
|
||||
/**
|
||||
* Holder for the calling BeanFactory
|
||||
* @see #postProcessBeanFactory(ConfigurableListableBeanFactory)
|
||||
*/
|
||||
private DefaultListableBeanFactory beanFactory;
|
||||
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
|
||||
|
||||
|
||||
/**
|
||||
* @return {@link Ordered#HIGHEST_PRECEDENCE}.
|
||||
* Override the default {@link ProblemReporter}.
|
||||
* @param problemReporter custom problem reporter
|
||||
*/
|
||||
public void setProblemReporter(ProblemReporter problemReporter) {
|
||||
this.problemReporter = problemReporter;
|
||||
}
|
||||
|
||||
public void setBeanClassLoader(ClassLoader beanClassLoader) {
|
||||
this.beanClassLoader = beanClassLoader;
|
||||
}
|
||||
|
||||
public int getOrder() {
|
||||
return Ordered.HIGHEST_PRECEDENCE;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Finds {@link Configuration} bean definitions within <var>clBeanFactory</var>
|
||||
* and processes them in order to register bean definitions for each Bean method
|
||||
* found within; also prepares the the Configuration classes for servicing
|
||||
* bean requests at runtime by replacing them with CGLIB-enhanced subclasses.
|
||||
* Prepare the Configuration classes for servicing bean requests at runtime
|
||||
* by replacing them with CGLIB-enhanced subclasses.
|
||||
*/
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory clBeanFactory) throws BeansException {
|
||||
Assert.isInstanceOf(DefaultListableBeanFactory.class, clBeanFactory);
|
||||
beanFactory = (DefaultListableBeanFactory) clBeanFactory;
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
|
||||
if (!(beanFactory instanceof BeanDefinitionRegistry)) {
|
||||
throw new IllegalStateException(
|
||||
"ConfigurationClassPostProcessor expects a BeanFactory that implements BeanDefinitionRegistry");
|
||||
}
|
||||
processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
|
||||
enhanceConfigurationClasses(beanFactory);
|
||||
}
|
||||
|
||||
BeanDefinitionRegistry factoryBeanDefs = processConfigBeanDefinitions();
|
||||
|
||||
for(String beanName : factoryBeanDefs.getBeanDefinitionNames())
|
||||
beanFactory.registerBeanDefinition(beanName, factoryBeanDefs.getBeanDefinition(beanName));
|
||||
/**
|
||||
* Build and validate a configuration model based on the registry of
|
||||
* {@link Configuration} classes.
|
||||
*/
|
||||
protected final void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
|
||||
Set<BeanDefinitionHolder> configBeanDefs = new LinkedHashSet<BeanDefinitionHolder>();
|
||||
for (String beanName : registry.getBeanDefinitionNames()) {
|
||||
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
|
||||
if (checkConfigurationClassBeanDefinition(beanDef)) {
|
||||
configBeanDefs.add(new BeanDefinitionHolder(beanDef, beanName));
|
||||
}
|
||||
}
|
||||
|
||||
enhanceConfigurationClasses();
|
||||
// Return immediately if no @Configuration classes were found
|
||||
if (configBeanDefs.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Populate a new configuration model by parsing each @Configuration classes
|
||||
ConfigurationClassParser parser = new ConfigurationClassParser(this.problemReporter, this.beanClassLoader);
|
||||
for (BeanDefinitionHolder holder : configBeanDefs) {
|
||||
parser.parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
|
||||
}
|
||||
parser.validate();
|
||||
|
||||
// Read the model and create bean definitions based on its content
|
||||
new ConfigurationClassBeanDefinitionReader(registry).loadBeanDefinitions(parser.getModel());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return a ConfigurationParser that uses the enclosing BeanFactory's
|
||||
* ClassLoader to load all Configuration class artifacts.
|
||||
* Post-processes a BeanFactory in search of Configuration class BeanDefinitions;
|
||||
* any candidates are then enhanced by a {@link ConfigurationClassEnhancer}.
|
||||
* Candidate status is determined by BeanDefinition attribute metadata.
|
||||
* @see ConfigurationClassEnhancer
|
||||
*/
|
||||
@Override
|
||||
protected ConfigurationClassParser createConfigurationParser() {
|
||||
return new ConfigurationClassParser(this.getProblemReporter(), beanFactory.getBeanClassLoader());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return map of all non-abstract {@link BeanDefinition}s in the
|
||||
* enclosing {@link #beanFactory}
|
||||
*/
|
||||
@Override
|
||||
protected BeanDefinitionRegistry getConfigurationBeanDefinitions(boolean includeAbstractBeanDefs) {
|
||||
|
||||
BeanDefinitionRegistry configBeanDefs = new DefaultListableBeanFactory();
|
||||
|
||||
private void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
|
||||
Set<BeanDefinitionHolder> configBeanDefs = new LinkedHashSet<BeanDefinitionHolder>();
|
||||
for (String beanName : beanFactory.getBeanDefinitionNames()) {
|
||||
BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
|
||||
|
||||
if (beanDef.isAbstract() && !includeAbstractBeanDefs)
|
||||
continue;
|
||||
|
||||
if (isConfigurationClassBeanDefinition(beanDef, beanFactory.getBeanClassLoader()))
|
||||
configBeanDefs.registerBeanDefinition(beanName, beanDef);
|
||||
if ("full".equals(beanDef.getAttribute(CONFIGURATION_CLASS_ATTRIBUTE))) {
|
||||
configBeanDefs.add(new BeanDefinitionHolder(beanDef, beanName));
|
||||
}
|
||||
}
|
||||
|
||||
return configBeanDefs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Post-processes a BeanFactory in search of Configuration class BeanDefinitions; any
|
||||
* candidates are then enhanced by a {@link ConfigurationClassEnhancer}. Candidate status is
|
||||
* determined by BeanDefinition attribute metadata.
|
||||
*
|
||||
* @see ConfigurationClassEnhancer
|
||||
* @see BeanFactoryPostProcessor
|
||||
*/
|
||||
private void enhanceConfigurationClasses() {
|
||||
|
||||
BeanDefinitionRegistry configBeanDefs = getConfigurationBeanDefinitions(true);
|
||||
|
||||
if (configBeanDefs.getBeanDefinitionCount() == 0)
|
||||
if (configBeanDefs.isEmpty()) {
|
||||
// nothing to enhance -> return immediately
|
||||
return;
|
||||
|
||||
assertCglibIsPresent(configBeanDefs);
|
||||
|
||||
ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer(beanFactory);
|
||||
|
||||
for (String beanName : configBeanDefs.getBeanDefinitionNames()) {
|
||||
BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
|
||||
String configClassName = beanDef.getBeanClassName();
|
||||
String enhancedClassName = enhancer.enhance(configClassName);
|
||||
|
||||
if (logger.isDebugEnabled())
|
||||
logger.debug(format("Replacing bean definition '%s' existing class name '%s' "
|
||||
+ "with enhanced class name '%s'", beanName, configClassName, enhancedClassName));
|
||||
|
||||
beanDef.setBeanClassName(enhancedClassName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests for the presence of CGLIB on the classpath by trying to
|
||||
* classload {@link #CGLIB_TEST_CLASS}.
|
||||
* @throws IllegalStateException if CGLIB is not present.
|
||||
*/
|
||||
private void assertCglibIsPresent(BeanDefinitionRegistry configBeanDefs) {
|
||||
try {
|
||||
Class.forName(CGLIB_TEST_CLASS);
|
||||
} catch (ClassNotFoundException e) {
|
||||
if (!cglibAvailable) {
|
||||
Set<String> beanNames = new LinkedHashSet<String>();
|
||||
for (BeanDefinitionHolder holder : configBeanDefs) {
|
||||
beanNames.add(holder.getBeanName());
|
||||
}
|
||||
throw new IllegalStateException("CGLIB is required to process @Configuration classes. " +
|
||||
"Either add CGLIB to the classpath or remove the following @Configuration bean definitions: [" +
|
||||
StringUtils.arrayToCommaDelimitedString(configBeanDefs.getBeanDefinitionNames()) + "]");
|
||||
"Either add CGLIB to the classpath or remove the following @Configuration bean definitions: " +
|
||||
beanNames);
|
||||
}
|
||||
ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer(beanFactory);
|
||||
for (BeanDefinitionHolder holder : configBeanDefs) {
|
||||
AbstractBeanDefinition beanDef = (AbstractBeanDefinition) holder.getBeanDefinition();
|
||||
try {
|
||||
Class configClass = beanDef.resolveBeanClass(this.beanClassLoader);
|
||||
Class enhancedClass = enhancer.enhance(configClass);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug(String.format("Replacing bean definition '%s' existing class name '%s' " +
|
||||
"with enhanced class name '%s'", holder.getBeanName(), configClass.getName(), enhancedClass.getName()));
|
||||
}
|
||||
beanDef.setBeanClass(enhancedClass);
|
||||
}
|
||||
catch (ClassNotFoundException ex) {
|
||||
throw new IllegalStateException("Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,29 +191,41 @@ public class ConfigurationClassPostProcessor extends AbstractConfigurationClassP
|
||||
* @return whether the BeanDefinition's beanClass (or its ancestry) is
|
||||
* {@link Configuration}-annotated, false if no beanClass is specified.
|
||||
*/
|
||||
private static boolean isConfigurationClassBeanDefinition(BeanDefinition beanDef, ClassLoader classLoader) {
|
||||
|
||||
private boolean checkConfigurationClassBeanDefinition(BeanDefinition beanDef) {
|
||||
// accommodating SPR-5655
|
||||
Assert.isInstanceOf(AbstractBeanDefinition.class, beanDef);
|
||||
if(((AbstractBeanDefinition) beanDef).hasBeanClass())
|
||||
return AnnotationUtils.findAnnotation(
|
||||
((AbstractBeanDefinition)beanDef).getBeanClass(), Configuration.class) != null;
|
||||
|
||||
if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
|
||||
if (AnnotationUtils.findAnnotation(
|
||||
((AbstractBeanDefinition) beanDef).getBeanClass(), Configuration.class) != null) {
|
||||
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, "full");
|
||||
return true;
|
||||
}
|
||||
else if (AnnotationUtils.findAnnotation(
|
||||
((AbstractBeanDefinition) beanDef).getBeanClass(), Component.class) != null) {
|
||||
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, "lite");
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(this.beanClassLoader);
|
||||
String className = beanDef.getBeanClassName();
|
||||
|
||||
while (className != null && !(className.equals(Object.class.getName()))) {
|
||||
try {
|
||||
MetadataReader metadataReader =
|
||||
new SimpleMetadataReaderFactory(classLoader).getMetadataReader(className);
|
||||
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
|
||||
ClassMetadata classMetadata = metadataReader.getClassMetadata();
|
||||
|
||||
if (annotationMetadata.hasAnnotation(Configuration.class.getName()))
|
||||
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
|
||||
AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
|
||||
if (metadata.hasAnnotation(Configuration.class.getName())) {
|
||||
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, "full");
|
||||
return true;
|
||||
|
||||
className = classMetadata.getSuperClassName();
|
||||
} catch (IOException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
if (metadata.hasAnnotation(Component.class.getName())) {
|
||||
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, "lite");
|
||||
return true;
|
||||
}
|
||||
className = metadata.getSuperClassName();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new BeanDefinitionStoreException("Failed to load class file [" + className + "]", ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import static java.lang.String.*;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.asm.ClassReader;
|
||||
import org.springframework.beans.factory.BeanDefinitionStoreException;
|
||||
import static org.springframework.core.annotation.AnnotationUtils.*;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Various utility methods commonly used when interacting with ASM, classloading
|
||||
* and creating {@link ConfigurationClassAnnotation} instances.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @since 3.0
|
||||
*/
|
||||
class ConfigurationClassReaderUtils {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(ConfigurationClassReaderUtils.class);
|
||||
|
||||
/**
|
||||
* Convert a type descriptor to a classname suitable for classloading with
|
||||
* Class.forName().
|
||||
*
|
||||
* @param typeDescriptor see ASM guide section 2.1.3
|
||||
*/
|
||||
public static String convertAsmTypeDescriptorToClassName(String typeDescriptor) {
|
||||
final String internalName; // See ASM guide section 2.1.2
|
||||
|
||||
if ("V".equals(typeDescriptor))
|
||||
return Void.class.getName();
|
||||
if ("I".equals(typeDescriptor))
|
||||
return Integer.class.getName();
|
||||
if ("Z".equals(typeDescriptor))
|
||||
return Boolean.class.getName();
|
||||
|
||||
// strip the leading array/object/primitive identifier
|
||||
if (typeDescriptor.startsWith("[["))
|
||||
internalName = typeDescriptor.substring(3);
|
||||
else if (typeDescriptor.startsWith("["))
|
||||
internalName = typeDescriptor.substring(2);
|
||||
else
|
||||
internalName = typeDescriptor.substring(1);
|
||||
|
||||
// convert slashes to dots
|
||||
String className = internalName.replace('/', '.');
|
||||
|
||||
// and strip trailing semicolon (if present)
|
||||
if (className.endsWith(";"))
|
||||
className = className.substring(0, internalName.length() - 1);
|
||||
|
||||
return className;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param methodDescriptor see ASM guide section 2.1.4
|
||||
*/
|
||||
public static String getReturnTypeFromAsmMethodDescriptor(String methodDescriptor) {
|
||||
String returnTypeDescriptor = methodDescriptor.substring(methodDescriptor.indexOf(')') + 1);
|
||||
return convertAsmTypeDescriptorToClassName(returnTypeDescriptor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new ASM {@link ClassReader} for <var>pathToClass</var>. Appends '.class' to
|
||||
* pathToClass before attempting to load.
|
||||
*/
|
||||
public static ClassReader newAsmClassReader(String pathToClass, ClassLoader classLoader) {
|
||||
InputStream is = getClassAsStream(pathToClass, classLoader);
|
||||
return newAsmClassReader(is);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method that creates and returns a new ASM {@link ClassReader} for the
|
||||
* given InputStream <var>is</var>, closing the InputStream after creating the
|
||||
* ClassReader and rethrowing any IOException thrown during ClassReader instantiation as
|
||||
* an unchecked exception. Logs and ignores any IOException thrown when closing the
|
||||
* InputStream.
|
||||
*
|
||||
* @param is InputStream that will be provided to the new ClassReader instance.
|
||||
*/
|
||||
public static ClassReader newAsmClassReader(InputStream is) {
|
||||
try {
|
||||
return new ClassReader(is);
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new BeanDefinitionStoreException("An unexpected exception occurred while creating ASM ClassReader: " + ex);
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
is.close();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses the default ClassLoader to load <var>pathToClass</var>. Appends '.class' to
|
||||
* pathToClass before attempting to load.
|
||||
* @param pathToClass resource path to class, not including .class suffix. e.g.: com/acme/MyClass
|
||||
* @return inputStream for <var>pathToClass</var>
|
||||
* @throws RuntimeException if <var>pathToClass</var> does not exist
|
||||
*/
|
||||
public static InputStream getClassAsStream(String pathToClass, ClassLoader classLoader) {
|
||||
String classFileName = pathToClass + ClassUtils.CLASS_FILE_SUFFIX;
|
||||
InputStream is = classLoader.getResourceAsStream(classFileName);
|
||||
if (is == null) {
|
||||
throw new IllegalStateException("Class file [" + classFileName + "] not found");
|
||||
}
|
||||
return is;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the specified class using the default class loader, gracefully handling any
|
||||
* {@link ClassNotFoundException} that may be thrown by issuing a WARN level logging
|
||||
* statement and return null. This functionality is specifically implemented to
|
||||
* accomodate tooling (Spring IDE) concerns, where user-defined types will not be
|
||||
* available to the tooling.
|
||||
* <p>
|
||||
* Because {@link ClassNotFoundException} is compensated for by returning null, callers
|
||||
* must take care to handle the null case appropriately.
|
||||
* <p>
|
||||
* In cases where the WARN logging statement is not desired, use the
|
||||
* {@link #loadClass(String)} method, which returns null but issues no logging
|
||||
* statements.
|
||||
* <p>
|
||||
* This method should only ever return null in the case of a user-defined type be
|
||||
* processed at tooling time. Therefore, tooling may not be able to represent any custom
|
||||
* annotation semantics, but JavaConfig itself will not have any problem loading and
|
||||
* respecting them at actual runtime.
|
||||
*
|
||||
* @param <T> type of class to be returned
|
||||
* @param fqClassName fully-qualified class name
|
||||
*
|
||||
* @return newly loaded class, null if class could not be found.
|
||||
*
|
||||
* @see #loadClass(String)
|
||||
* @see #loadRequiredClass(String)
|
||||
* @see ClassUtils#getDefaultClassLoader()
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Class<? extends T> loadToolingSafeClass(String fqClassName, ClassLoader classLoader) {
|
||||
try {
|
||||
return (Class<? extends T>) classLoader.loadClass(fqClassName);
|
||||
}
|
||||
catch (ClassNotFoundException ex) {
|
||||
logger.warn(String.format("Unable to load class [%s], likely due to tooling-specific restrictions."
|
||||
+ "Attempting to continue, but unexpected errors may occur", fqClassName), ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link ConfigurationClassAnnotation} for {@code annoType}. JDK dynamic proxies are used,
|
||||
* and the returned proxy implements both {@link ConfigurationClassAnnotation} and the annotation type.
|
||||
* @param annoType annotation type that must be supplied and returned
|
||||
* @param annoType type of annotation to create
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static ConfigurationClassAnnotation createMutableAnnotation(Class<? extends Annotation> annoType, ClassLoader classLoader) {
|
||||
MutableAnnotationInvocationHandler handler = new MutableAnnotationInvocationHandler(annoType);
|
||||
Class<?>[] interfaces = new Class<?>[] {annoType, ConfigurationClassAnnotation.class};
|
||||
return (ConfigurationClassAnnotation) Proxy.newProxyInstance(classLoader, interfaces, handler);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handles calls to {@link ConfigurationClassAnnotation} attribute methods at runtime. Essentially
|
||||
* emulates what JDK annotation dynamic proxies do.
|
||||
*/
|
||||
private static final class MutableAnnotationInvocationHandler implements InvocationHandler {
|
||||
|
||||
private final Class<? extends Annotation> annoType;
|
||||
private final Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
private final Map<String, Class<?>> attributeTypes = new HashMap<String, Class<?>>();
|
||||
|
||||
public MutableAnnotationInvocationHandler(Class<? extends Annotation> annoType) {
|
||||
// pre-populate the attributes hash will all the names
|
||||
// and default values of the attributes defined in 'annoType'
|
||||
Method[] attribs = annoType.getDeclaredMethods();
|
||||
for (Method attrib : attribs) {
|
||||
this.attributes.put(attrib.getName(), getDefaultValue(annoType, attrib.getName()));
|
||||
this.attributeTypes.put(attrib.getName(), getAttributeType(annoType, attrib.getName()));
|
||||
}
|
||||
|
||||
this.annoType = annoType;
|
||||
}
|
||||
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
Assert.isInstanceOf(Annotation.class, proxy);
|
||||
|
||||
String methodName = method.getName();
|
||||
|
||||
// first -> check to see if this method is an attribute on our annotation
|
||||
if (attributes.containsKey(methodName))
|
||||
return attributes.get(methodName);
|
||||
|
||||
|
||||
// second -> is it a method from java.lang.annotation.Annotation?
|
||||
if (methodName.equals("annotationType"))
|
||||
return annoType;
|
||||
|
||||
|
||||
// third -> is it a method from java.lang.Object?
|
||||
if (methodName.equals("toString"))
|
||||
return format("@%s(%s)", annoType.getName(), getAttribs());
|
||||
|
||||
if (methodName.equals("equals"))
|
||||
return isEqualTo(proxy, args[0]);
|
||||
|
||||
if (methodName.equals("hashCode"))
|
||||
return calculateHashCode(proxy);
|
||||
|
||||
|
||||
// finally -> is it a method specified by MutableAnno?
|
||||
if (methodName.equals("setAttributeValue")) {
|
||||
attributes.put((String) args[0], args[1]);
|
||||
return null; // setAttributeValue has a 'void' return type
|
||||
}
|
||||
|
||||
if (methodName.equals("getAttributeType"))
|
||||
return attributeTypes.get(args[0]);
|
||||
|
||||
throw new UnsupportedOperationException("this proxy does not support method: " + methodName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Conforms to the hashCode() specification for Annotation.
|
||||
*
|
||||
* @see Annotation#hashCode()
|
||||
*/
|
||||
private Object calculateHashCode(Object proxy) {
|
||||
int sum = 0;
|
||||
|
||||
for (String attribName : attributes.keySet()) {
|
||||
Object attribValue = attributes.get(attribName);
|
||||
|
||||
final int attribNameHashCode = attribName.hashCode();
|
||||
final int attribValueHashCode;
|
||||
|
||||
if (attribValue == null)
|
||||
// memberValue may be null when a mutable annotation is being added to a
|
||||
// collection
|
||||
// and before it has actually been visited (and populated) by
|
||||
// MutableAnnotationVisitor
|
||||
attribValueHashCode = 0;
|
||||
else if (attribValue.getClass().isArray())
|
||||
attribValueHashCode = Arrays.hashCode((Object[]) attribValue);
|
||||
else
|
||||
attribValueHashCode = attribValue.hashCode();
|
||||
|
||||
sum += (127 * attribNameHashCode) ^ attribValueHashCode;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares <var>proxy</var> object and <var>other</var> object by comparing the return
|
||||
* values of the methods specified by their common {@link Annotation} ancestry.
|
||||
* <p/>
|
||||
* <var>other</var> must be the same type as or a subtype of <var>proxy</var>. Will
|
||||
* return false otherwise.
|
||||
* <p/>
|
||||
* Eagerly returns true if {@code proxy} == <var>other</var>
|
||||
* </p>
|
||||
* <p/>
|
||||
* Conforms strictly to the equals() specification for Annotation
|
||||
* </p>
|
||||
*
|
||||
* @see Annotation#equals(Object)
|
||||
*/
|
||||
private Object isEqualTo(Object proxy, Object other) {
|
||||
if (proxy == other)
|
||||
return true;
|
||||
|
||||
if (other == null)
|
||||
return false;
|
||||
|
||||
if (!annoType.isAssignableFrom(other.getClass()))
|
||||
return false;
|
||||
|
||||
for (String attribName : attributes.keySet()) {
|
||||
Object thisVal;
|
||||
Object thatVal;
|
||||
|
||||
try {
|
||||
thisVal = attributes.get(attribName);
|
||||
thatVal = other.getClass().getDeclaredMethod(attribName).invoke(other);
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
|
||||
if ((thisVal == null) && (thatVal != null))
|
||||
return false;
|
||||
|
||||
if ((thatVal == null) && (thisVal != null))
|
||||
return false;
|
||||
|
||||
if (thatVal.getClass().isArray()) {
|
||||
if (!Arrays.equals((Object[]) thatVal, (Object[]) thisVal)) {
|
||||
return false;
|
||||
}
|
||||
} else if (thisVal instanceof Double) {
|
||||
if (!Double.valueOf((Double) thisVal).equals(Double.valueOf((Double) thatVal)))
|
||||
return false;
|
||||
} else if (thisVal instanceof Float) {
|
||||
if (!Float.valueOf((Float) thisVal).equals(Float.valueOf((Float) thatVal)))
|
||||
return false;
|
||||
} else if (!thisVal.equals(thatVal)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private String getAttribs() {
|
||||
ArrayList<String> attribs = new ArrayList<String>();
|
||||
|
||||
for (String attribName : attributes.keySet())
|
||||
attribs.add(format("%s=%s", attribName, attributes.get(attribName)));
|
||||
|
||||
return StringUtils.collectionToDelimitedString(attribs, ", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the type of the given annotation attribute.
|
||||
*/
|
||||
private static Class<?> getAttributeType(Class<? extends Annotation> annotationType, String attributeName) {
|
||||
Method method = null;
|
||||
|
||||
try {
|
||||
method = annotationType.getDeclaredMethod(attributeName);
|
||||
} catch (Exception ex) {
|
||||
ReflectionUtils.handleReflectionException(ex);
|
||||
}
|
||||
|
||||
return method.getReturnType();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,75 +16,83 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
import static org.springframework.context.annotation.AsmUtils.*;
|
||||
import static org.springframework.util.ClassUtils.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.Stack;
|
||||
|
||||
import org.springframework.asm.AnnotationVisitor;
|
||||
import org.springframework.asm.Attribute;
|
||||
import org.springframework.asm.ClassAdapter;
|
||||
import org.springframework.asm.ClassReader;
|
||||
import org.springframework.asm.ClassVisitor;
|
||||
import org.springframework.asm.FieldVisitor;
|
||||
import org.springframework.asm.Label;
|
||||
import org.springframework.asm.MethodAdapter;
|
||||
import org.springframework.asm.MethodVisitor;
|
||||
import org.springframework.asm.Opcodes;
|
||||
import org.springframework.asm.Type;
|
||||
import org.springframework.asm.commons.EmptyVisitor;
|
||||
import org.springframework.beans.factory.parsing.Location;
|
||||
import org.springframework.beans.factory.parsing.Problem;
|
||||
import org.springframework.beans.factory.parsing.ProblemReporter;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* ASM {@link ClassVisitor} that visits a {@link Configuration} class, populating a
|
||||
* {@link ConfigurationClass} instance with information gleaned along the way.
|
||||
*
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
* @see ConfigurationClassParser
|
||||
* @see ConfigurationClass
|
||||
*/
|
||||
class ConfigurationClassVisitor extends ClassAdapter {
|
||||
class ConfigurationClassVisitor implements ClassVisitor {
|
||||
|
||||
private static final String OBJECT_DESC = convertClassNameToResourcePath(Object.class.getName());
|
||||
private static final String OBJECT_DESC = ClassUtils.convertClassNameToResourcePath(Object.class.getName());
|
||||
|
||||
private final ConfigurationClass configClass;
|
||||
private final ConfigurationModel model;
|
||||
|
||||
private final Set<ConfigurationClass> model;
|
||||
|
||||
private final ProblemReporter problemReporter;
|
||||
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
private final HashMap<String, ConfigurationClass> innerClasses = new HashMap<String, ConfigurationClass>();
|
||||
private final Stack<ConfigurationClass> importStack;
|
||||
|
||||
private boolean processInnerClasses = true;
|
||||
|
||||
public ConfigurationClassVisitor(ConfigurationClass configClass, ConfigurationModel model,
|
||||
ProblemReporter problemReporter, ClassLoader classLoader) {
|
||||
super(ASM_EMPTY_VISITOR);
|
||||
public ConfigurationClassVisitor(ConfigurationClass configClass, Set<ConfigurationClass> model,
|
||||
ProblemReporter problemReporter, ClassLoader classLoader) {
|
||||
|
||||
this.configClass = configClass;
|
||||
this.model = model;
|
||||
this.problemReporter = problemReporter;
|
||||
this.classLoader = classLoader;
|
||||
this.importStack = new ImportStack();
|
||||
}
|
||||
|
||||
public void setProcessInnerClasses(boolean processInnerClasses) {
|
||||
this.processInnerClasses = processInnerClasses;
|
||||
private ConfigurationClassVisitor(ConfigurationClass configClass, Set<ConfigurationClass> model,
|
||||
ProblemReporter problemReporter, ClassLoader classLoader, Stack<ConfigurationClass> importStack) {
|
||||
this.configClass = configClass;
|
||||
this.model = model;
|
||||
this.problemReporter = problemReporter;
|
||||
this.classLoader = classLoader;
|
||||
this.importStack = importStack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitSource(String sourceFile, String debug) {
|
||||
String resourcePath =
|
||||
convertClassNameToResourcePath(configClass.getName())
|
||||
.substring(0, configClass.getName().lastIndexOf('.') + 1).concat(sourceFile);
|
||||
|
||||
configClass.setSource(resourcePath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(int classVersion, int modifiers, String classTypeDesc, String arg3,
|
||||
String superTypeDesc, String[] arg5) {
|
||||
public void visit(int classVersion, int modifiers, String classTypeDesc, String arg3, String superTypeDesc, String[] arg5) {
|
||||
visitSuperType(superTypeDesc);
|
||||
|
||||
configClass.setName(convertResourcePathToClassName(classTypeDesc));
|
||||
configClass.setName(ClassUtils.convertResourcePathToClassName(classTypeDesc));
|
||||
|
||||
// ASM always adds ACC_SUPER to the opcodes/modifiers for class definitions.
|
||||
// Unknown as to why (JavaDoc is silent on the matter), but it should be
|
||||
@@ -94,128 +102,327 @@ class ConfigurationClassVisitor extends ClassAdapter {
|
||||
|
||||
private void visitSuperType(String superTypeDesc) {
|
||||
// traverse up the type hierarchy unless the next ancestor is java.lang.Object
|
||||
if (OBJECT_DESC.equals(superTypeDesc))
|
||||
if (OBJECT_DESC.equals(superTypeDesc)) {
|
||||
return;
|
||||
|
||||
ConfigurationClassVisitor visitor =
|
||||
new ConfigurationClassVisitor(configClass, model, problemReporter, classLoader);
|
||||
|
||||
ClassReader reader = newAsmClassReader(superTypeDesc, classLoader);
|
||||
}
|
||||
ConfigurationClassVisitor visitor = new ConfigurationClassVisitor(configClass, model, problemReporter, classLoader, importStack);
|
||||
ClassReader reader = ConfigurationClassReaderUtils.newAsmClassReader(superTypeDesc, classLoader);
|
||||
reader.accept(visitor, false);
|
||||
}
|
||||
|
||||
public void visitSource(String sourceFile, String debug) {
|
||||
String resourcePath =
|
||||
ClassUtils.convertClassNameToResourcePath(configClass.getName())
|
||||
.substring(0, configClass.getName().lastIndexOf('.') + 1).concat(sourceFile);
|
||||
|
||||
configClass.setSource(resourcePath);
|
||||
}
|
||||
|
||||
public void visitOuterClass(String s, String s1, String s2) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a class level annotation on a {@link Configuration @Configuration} class.
|
||||
*
|
||||
* <p>Upon encountering such an annotation, updates the {@link #configClass} model
|
||||
* object appropriately, and then returns an {@link AnnotationVisitor} implementation
|
||||
* that can populate the annotation appropriately with its attribute data as parsed
|
||||
* by ASM.
|
||||
*
|
||||
* @see MutableAnnotation
|
||||
* @see ConfigurationClassAnnotation
|
||||
* @see Configuration
|
||||
* @see Lazy
|
||||
* @see Import
|
||||
*/
|
||||
@Override
|
||||
public AnnotationVisitor visitAnnotation(String annoTypeDesc, boolean visible) {
|
||||
String annoTypeName = convertAsmTypeDescriptorToClassName(annoTypeDesc);
|
||||
Class<? extends Annotation> annoClass = loadToolingSafeClass(annoTypeName, classLoader);
|
||||
String annoTypeName = ConfigurationClassReaderUtils.convertAsmTypeDescriptorToClassName(annoTypeDesc);
|
||||
Class<? extends Annotation> annoClass = ConfigurationClassReaderUtils.loadToolingSafeClass(annoTypeName, classLoader);
|
||||
|
||||
if (annoClass == null)
|
||||
if (annoClass == null) {
|
||||
// annotation was unable to be loaded -> probably Spring IDE unable to load a user-defined annotation
|
||||
return super.visitAnnotation(annoTypeDesc, visible);
|
||||
return new EmptyVisitor();
|
||||
}
|
||||
|
||||
if (Import.class.equals(annoClass)) {
|
||||
ImportStack importStack = ImportStackHolder.getImportStack();
|
||||
|
||||
if (!importStack.contains(configClass)) {
|
||||
importStack.push(configClass);
|
||||
return new ImportAnnotationVisitor(model, problemReporter, classLoader);
|
||||
}
|
||||
|
||||
problemReporter.error(new CircularImportProblem(configClass, importStack));
|
||||
}
|
||||
|
||||
Annotation mutableAnnotation = createMutableAnnotation(annoClass, classLoader);
|
||||
ConfigurationClassAnnotation mutableAnnotation = ConfigurationClassReaderUtils.createMutableAnnotation(annoClass, classLoader);
|
||||
configClass.addAnnotation(mutableAnnotation);
|
||||
return new MutableAnnotationVisitor(mutableAnnotation, classLoader);
|
||||
return new ConfigurationClassAnnotationVisitor(mutableAnnotation, classLoader);
|
||||
}
|
||||
|
||||
public void visitAttribute(Attribute attribute) {
|
||||
}
|
||||
|
||||
public void visitInnerClass(String s, String s1, String s2, int i) {
|
||||
}
|
||||
|
||||
public FieldVisitor visitField(int i, String s, String s1, String s2, Object o) {
|
||||
return new EmptyVisitor();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates all {@link Configuration @Configuration} class method parsing to
|
||||
* {@link ConfigurationClassMethodVisitor}.
|
||||
*/
|
||||
@Override
|
||||
public MethodVisitor visitMethod(int modifiers, String methodName, String methodDescriptor,
|
||||
String arg3, String[] arg4) {
|
||||
|
||||
public MethodVisitor visitMethod(int modifiers, String methodName, String methodDescriptor, String arg3, String[] arg4) {
|
||||
return new ConfigurationClassMethodVisitor(configClass, methodName, methodDescriptor, modifiers, classLoader);
|
||||
}
|
||||
|
||||
public void visitEnd() {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Implementation deals with inner classes here even though it would have been more
|
||||
* intuitive to deal with outer classes. Due to limitations in ASM (resulting from
|
||||
* limitations in the VM spec) we cannot directly look for outer classes in all cases,
|
||||
* so instead build up a model of {@link #innerClasses} and process declaring class
|
||||
* logic in a kind of inverted manner.
|
||||
* ASM {@link MethodVisitor} that visits a single method declared in a given
|
||||
* {@link Configuration} class. Determines whether the method is a {@link Bean}
|
||||
* method and if so, adds it to the {@link ConfigurationClass}.
|
||||
*/
|
||||
@Override
|
||||
public void visitInnerClass(String name, String outerName, String innerName, int access) {
|
||||
if (processInnerClasses == false)
|
||||
return;
|
||||
private static class ConfigurationClassMethodVisitor extends MethodAdapter {
|
||||
|
||||
String innerClassName = convertResourcePathToClassName(name);
|
||||
String configClassName = configClass.getName();
|
||||
private final ConfigurationClass configClass;
|
||||
private final String methodName;
|
||||
private final int modifiers;
|
||||
private final ConfigurationClassMethod.ReturnType returnType;
|
||||
private final List<Annotation> annotations = new ArrayList<Annotation>();
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
// if the innerClassName is equal to configClassName, we just
|
||||
// ran into the outermost inner class look up the outer class
|
||||
// associated with this
|
||||
if (innerClassName.equals(configClassName)) {
|
||||
if (innerClasses.containsKey(outerName)) {
|
||||
configClass.setDeclaringClass(innerClasses.get(outerName));
|
||||
}
|
||||
return;
|
||||
private int lineNumber;
|
||||
|
||||
/**
|
||||
* Create a new {@link ConfigurationClassMethodVisitor} instance.
|
||||
* @param configClass model object to which this method will be added
|
||||
* @param methodName name of the method declared in the {@link Configuration} class
|
||||
* @param methodDescriptor ASM representation of the method signature
|
||||
* @param modifiers modifiers for this method
|
||||
*/
|
||||
public ConfigurationClassMethodVisitor(ConfigurationClass configClass, String methodName,
|
||||
String methodDescriptor, int modifiers, ClassLoader classLoader) {
|
||||
super(new EmptyVisitor());
|
||||
this.configClass = configClass;
|
||||
this.methodName = methodName;
|
||||
this.classLoader = classLoader;
|
||||
this.modifiers = modifiers;
|
||||
this.returnType = initReturnTypeFromMethodDescriptor(methodDescriptor);
|
||||
}
|
||||
|
||||
ConfigurationClass innerConfigClass = new ConfigurationClass();
|
||||
/**
|
||||
* Visits a single annotation on this method. Will be called once for each annotation
|
||||
* present (regardless of its RetentionPolicy).
|
||||
*/
|
||||
@Override
|
||||
public AnnotationVisitor visitAnnotation(String annoTypeDesc, boolean visible) {
|
||||
String annoClassName = ConfigurationClassReaderUtils.convertAsmTypeDescriptorToClassName(annoTypeDesc);
|
||||
Class<? extends Annotation> annoClass = ConfigurationClassReaderUtils.loadToolingSafeClass(annoClassName, classLoader);
|
||||
if (annoClass == null) {
|
||||
return super.visitAnnotation(annoTypeDesc, visible);
|
||||
}
|
||||
ConfigurationClassAnnotation annotation = ConfigurationClassReaderUtils.createMutableAnnotation(annoClass, classLoader);
|
||||
annotations.add(annotation);
|
||||
return new ConfigurationClassAnnotationVisitor(annotation, classLoader);
|
||||
}
|
||||
|
||||
ConfigurationClassVisitor ccVisitor =
|
||||
new ConfigurationClassVisitor(innerConfigClass, new ConfigurationModel(), problemReporter, classLoader);
|
||||
ccVisitor.setProcessInnerClasses(false);
|
||||
/**
|
||||
* Provides the line number of this method within its declaring class. In reality, this
|
||||
* number is always inaccurate - <var>lineNo</var> represents the line number of the
|
||||
* first instruction in this method. Method declaration line numbers are not in any way
|
||||
* tracked in the bytecode. Any tooling or output that reads this value will have to
|
||||
* compensate and estimate where the actual method declaration is.
|
||||
*/
|
||||
@Override
|
||||
public void visitLineNumber(int lineNo, Label start) {
|
||||
this.lineNumber = lineNo;
|
||||
}
|
||||
|
||||
ClassReader reader = newAsmClassReader(name, classLoader);
|
||||
reader.accept(ccVisitor, false);
|
||||
/**
|
||||
* Parses through all {@link #annotations} on this method in order to determine whether
|
||||
* it is a {@link Bean} method and if so adds it to the enclosing {@link #configClass}.
|
||||
*/
|
||||
@Override
|
||||
public void visitEnd() {
|
||||
for (Annotation anno : annotations) {
|
||||
if (Bean.class.equals(anno.annotationType())) {
|
||||
// this method is annotated with @Bean -> add it to the ConfigurationClass model
|
||||
Annotation[] annoArray = annotations.toArray(new Annotation[annotations.size()]);
|
||||
ConfigurationClassMethod method = new ConfigurationClassMethod(methodName, modifiers, returnType, annoArray);
|
||||
method.setSource(lineNumber);
|
||||
configClass.addMethod(method);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (innerClasses.containsKey(outerName))
|
||||
innerConfigClass.setDeclaringClass(innerClasses.get(outerName));
|
||||
/**
|
||||
* Determines return type from ASM <var>methodDescriptor</var> and determines whether
|
||||
* that type is an interface.
|
||||
*/
|
||||
private ConfigurationClassMethod.ReturnType initReturnTypeFromMethodDescriptor(String methodDescriptor) {
|
||||
final ConfigurationClassMethod.ReturnType returnType = new ConfigurationClassMethod.ReturnType(ConfigurationClassReaderUtils.getReturnTypeFromAsmMethodDescriptor(methodDescriptor));
|
||||
// detect whether the return type is an interface
|
||||
ConfigurationClassReaderUtils.newAsmClassReader(ClassUtils.convertClassNameToResourcePath(returnType.getName()), classLoader).accept(
|
||||
new ClassAdapter(new EmptyVisitor()) {
|
||||
@Override
|
||||
public void visit(int arg0, int arg1, String arg2, String arg3, String arg4, String[] arg5) {
|
||||
returnType.setInterface((arg1 & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE);
|
||||
}
|
||||
}, false);
|
||||
return returnType;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ASM {@link AnnotationVisitor} implementation that reads an {@link Import} annotation
|
||||
* for all its specified classes and then one by one processes each class with a new
|
||||
* {@link ConfigurationClassVisitor}.
|
||||
*/
|
||||
private class ImportAnnotationVisitor implements AnnotationVisitor{
|
||||
|
||||
private final Set<ConfigurationClass> model;
|
||||
|
||||
private final ProblemReporter problemReporter;
|
||||
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
private final List<String> classesToImport = new ArrayList<String>();
|
||||
|
||||
|
||||
public ImportAnnotationVisitor(
|
||||
Set<ConfigurationClass> model, ProblemReporter problemReporter, ClassLoader classLoader) {
|
||||
|
||||
this.model = model;
|
||||
this.problemReporter = problemReporter;
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
public void visit(String s, Object o) {
|
||||
}
|
||||
|
||||
public void visitEnum(String s, String s1, String s2) {
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitAnnotation(String s, String s1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitArray(String attribName) {
|
||||
Assert.isTrue("value".equals(attribName));
|
||||
return new AnnotationVisitor() {
|
||||
public void visit(String na, Object type) {
|
||||
Assert.isInstanceOf(Type.class, type);
|
||||
classesToImport.add(((Type) type).getClassName());
|
||||
}
|
||||
public void visitEnum(String s, String s1, String s2) {
|
||||
}
|
||||
public AnnotationVisitor visitAnnotation(String s, String s1) {
|
||||
return new EmptyVisitor();
|
||||
}
|
||||
public AnnotationVisitor visitArray(String s) {
|
||||
return new EmptyVisitor();
|
||||
}
|
||||
public void visitEnd() {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void visitEnd() {
|
||||
for (String classToImport : classesToImport) {
|
||||
processClassToImport(classToImport);
|
||||
}
|
||||
importStack.pop();
|
||||
}
|
||||
|
||||
private void processClassToImport(String classToImport) {
|
||||
ConfigurationClass configClass = new ConfigurationClass();
|
||||
ClassReader reader = ConfigurationClassReaderUtils.newAsmClassReader(ClassUtils.convertClassNameToResourcePath(classToImport), classLoader);
|
||||
reader.accept(new ConfigurationClassVisitor(configClass, model, problemReporter, classLoader, importStack), false);
|
||||
if (configClass.getAnnotation(Configuration.class) == null) {
|
||||
problemReporter.error(new NonAnnotatedConfigurationProblem(configClass.getName(), configClass.getLocation()));
|
||||
}
|
||||
else {
|
||||
model.add(configClass);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
private static class ImportStack extends Stack<ConfigurationClass> {
|
||||
|
||||
/**
|
||||
* Simplified contains() implementation that tests to see if any {@link ConfigurationClass}
|
||||
* exists within this stack that has the same name as <var>elem</var>. Elem must be of
|
||||
* type ConfigurationClass.
|
||||
*/
|
||||
@Override
|
||||
public boolean contains(Object elem) {
|
||||
if (!(elem instanceof ConfigurationClass)) {
|
||||
return false;
|
||||
}
|
||||
ConfigurationClass configClass = (ConfigurationClass) elem;
|
||||
Comparator<ConfigurationClass> comparator = new Comparator<ConfigurationClass>() {
|
||||
public int compare(ConfigurationClass first, ConfigurationClass second) {
|
||||
return first.getName().equals(second.getName()) ? 0 : 1;
|
||||
}
|
||||
};
|
||||
return (Collections.binarySearch(this, configClass, comparator) != -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a stack containing (in order)
|
||||
* <ol>
|
||||
* <li>com.acme.Foo</li>
|
||||
* <li>com.acme.Bar</li>
|
||||
* <li>com.acme.Baz</li>
|
||||
* </ol>
|
||||
* Returns "Foo->Bar->Baz". In the case of an empty stack, returns empty string.
|
||||
*/
|
||||
@Override
|
||||
public synchronized String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
Iterator<ConfigurationClass> iterator = iterator();
|
||||
while (iterator.hasNext()) {
|
||||
builder.append(iterator.next().getSimpleName());
|
||||
if (iterator.hasNext()) {
|
||||
builder.append("->");
|
||||
}
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Configuration classes must be annotated with {@link Configuration @Configuration}. */
|
||||
private static class NonAnnotatedConfigurationProblem extends Problem {
|
||||
|
||||
public NonAnnotatedConfigurationProblem(String className, Location location) {
|
||||
super(String.format("%s was imported as a @Configuration class but was not actually annotated " +
|
||||
"with @Configuration. Annotate the class or do not attempt to process it.", className), location);
|
||||
}
|
||||
|
||||
// is the inner class a @Configuration class? If so, add it to the list
|
||||
if (innerConfigClass.getAnnotation(Configuration.class) != null)
|
||||
innerClasses.put(name, innerConfigClass);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* {@link Problem} registered upon detection of a circular {@link Import}.
|
||||
*
|
||||
* @see Import
|
||||
* @see ImportStack
|
||||
* @see ImportStackHolder
|
||||
*/
|
||||
class CircularImportProblem extends Problem {
|
||||
private static class CircularImportProblem extends Problem {
|
||||
|
||||
CircularImportProblem(ConfigurationClass attemptedImport, Stack<ConfigurationClass> importStack) {
|
||||
super(format("A circular @Import has been detected: " +
|
||||
public CircularImportProblem(ConfigurationClass attemptedImport, Stack<ConfigurationClass> importStack) {
|
||||
super(String.format("A circular @Import has been detected: " +
|
||||
"Illegal attempt by @Configuration class '%s' to import class '%s' as '%s' is " +
|
||||
"already present in the current import stack [%s]",
|
||||
importStack.peek().getSimpleName(), attemptedImport.getSimpleName(),
|
||||
attemptedImport.getSimpleName(), importStack),
|
||||
new Location(new ClassPathResource(convertClassNameToResourcePath(importStack.peek().getName())),
|
||||
importStack.peek().getSource())
|
||||
new Location(new ClassPathResource(
|
||||
ClassUtils.convertClassNameToResourcePath(importStack.peek().getName())),
|
||||
importStack.peek().getSource())
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.parsing.ProblemReporter;
|
||||
|
||||
|
||||
/**
|
||||
* Represents the set of all user-defined {@link Configuration} classes. Once this model
|
||||
* is populated using a {@link ConfigurationClassParser}, it can be rendered out to a set of
|
||||
* {@link BeanDefinition} objects. This model provides an important layer of indirection
|
||||
* between the complexity of parsing a set of classes and the complexity of representing
|
||||
* the contents of those classes as BeanDefinitions.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see ConfigurationClass
|
||||
* @see ConfigurationClassParser
|
||||
* @see ConfigurationModelBeanDefinitionReader
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
final class ConfigurationModel extends LinkedHashSet<ConfigurationClass> {
|
||||
|
||||
/**
|
||||
* Recurses through the model validating each {@link ConfigurationClass}.
|
||||
*
|
||||
* @param problemReporter {@link ProblemReporter} against which any validation errors
|
||||
* will be registered
|
||||
* @see ConfigurationClass#validate
|
||||
*/
|
||||
public void validate(ProblemReporter problemReporter) {
|
||||
for (ConfigurationClass configClass : this)
|
||||
configClass.validate(problemReporter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return format("%s containing @Configuration classes: %s", getClass().getSimpleName(), super.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
import static org.springframework.util.StringUtils.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.aop.framework.autoproxy.AutoProxyUtils;
|
||||
import org.springframework.aop.scope.ScopedProxyFactoryBean;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.beans.factory.support.AbstractBeanDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionReader;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.beans.factory.support.GenericBeanDefinition;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
/**
|
||||
* Reads a given fully-populated {@link ConfigurationModel}, registering bean definitions
|
||||
* with the given {@link BeanDefinitionRegistry} based on its contents.
|
||||
* <p>
|
||||
* This class was modeled after the {@link BeanDefinitionReader} hierarchy, but does not
|
||||
* implement/extend any of its artifacts as {@link ConfigurationModel} is not a
|
||||
* {@link Resource}.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see ConfigurationModel
|
||||
* @see AbstractConfigurationClassProcessor#processConfigBeanDefinitions()
|
||||
*/
|
||||
class ConfigurationModelBeanDefinitionReader {
|
||||
|
||||
private static final Log log = LogFactory.getLog(ConfigurationModelBeanDefinitionReader.class);
|
||||
|
||||
private BeanDefinitionRegistry registry;
|
||||
|
||||
|
||||
/**
|
||||
* Reads {@code configurationModel}, registering bean definitions with {@link #registry}
|
||||
* based on its contents.
|
||||
*
|
||||
* @return new {@link BeanDefinitionRegistry} containing {@link BeanDefinition}s read
|
||||
* from the model.
|
||||
*/
|
||||
public BeanDefinitionRegistry loadBeanDefinitions(ConfigurationModel configurationModel) {
|
||||
registry = new SimpleBeanDefinitionRegistry();
|
||||
|
||||
for (ConfigurationClass configClass : configurationModel)
|
||||
loadBeanDefinitionsForConfigurationClass(configClass);
|
||||
|
||||
return registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a particular {@link ConfigurationClass}, registering bean definitions for the
|
||||
* class itself, all its {@link Bean} methods
|
||||
*/
|
||||
private void loadBeanDefinitionsForConfigurationClass(ConfigurationClass configClass) {
|
||||
doLoadBeanDefinitionForConfigurationClass(configClass);
|
||||
|
||||
for (BeanMethod method : configClass.getBeanMethods())
|
||||
loadBeanDefinitionsForModelMethod(method);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the {@link Configuration} class itself as a bean definition.
|
||||
* @param beanDefs
|
||||
*/
|
||||
private void doLoadBeanDefinitionForConfigurationClass(ConfigurationClass configClass) {
|
||||
|
||||
GenericBeanDefinition configBeanDef = new GenericBeanDefinition();
|
||||
configBeanDef.setBeanClassName(configClass.getName());
|
||||
|
||||
String configBeanName = configClass.getBeanName();
|
||||
|
||||
// consider the case where it's already been defined (probably in XML)
|
||||
// and potentially has PropertyValues and ConstructorArgs)
|
||||
if (registry.containsBeanDefinition(configBeanName)) {
|
||||
if (log.isInfoEnabled())
|
||||
log.info(format("Copying property and constructor arg values from existing bean definition for "
|
||||
+ "@Configuration class %s to new bean definition", configBeanName));
|
||||
AbstractBeanDefinition existing = (AbstractBeanDefinition) registry.getBeanDefinition(configBeanName);
|
||||
configBeanDef.setPropertyValues(existing.getPropertyValues());
|
||||
configBeanDef.setConstructorArgumentValues(existing.getConstructorArgumentValues());
|
||||
configBeanDef.setResource(existing.getResource());
|
||||
}
|
||||
|
||||
if (log.isInfoEnabled())
|
||||
log.info(format("Registering bean definition for @Configuration class %s", configBeanName));
|
||||
|
||||
registry.registerBeanDefinition(configBeanName, configBeanDef);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a particular {@link BeanMethod}, registering bean definitions with
|
||||
* {@link #registry} based on its contents.
|
||||
*/
|
||||
private void loadBeanDefinitionsForModelMethod(BeanMethod method) {
|
||||
RootBeanDefinition beanDef = new ConfigurationClassBeanDefinition();
|
||||
|
||||
ConfigurationClass configClass = method.getDeclaringClass();
|
||||
|
||||
beanDef.setFactoryBeanName(configClass.getBeanName());
|
||||
beanDef.setFactoryMethodName(method.getName());
|
||||
|
||||
Bean bean = method.getRequiredAnnotation(Bean.class);
|
||||
|
||||
// consider scoping
|
||||
Scope scope = method.getAnnotation(Scope.class);
|
||||
if(scope != null)
|
||||
beanDef.setScope(scope.value());
|
||||
|
||||
// consider name and any aliases
|
||||
ArrayList<String> names = new ArrayList<String>(Arrays.asList(bean.name()));
|
||||
String beanName = (names.size() > 0) ? names.remove(0) : method.getName();
|
||||
for (String alias : bean.name())
|
||||
registry.registerAlias(beanName, alias);
|
||||
|
||||
// has this already been overriden (i.e.: via XML)?
|
||||
if (containsBeanDefinitionIncludingAncestry(beanName, registry)) {
|
||||
BeanDefinition existingBeanDef = getBeanDefinitionIncludingAncestry(beanName, registry);
|
||||
|
||||
// is the existing bean definition one that was created by JavaConfig?
|
||||
if (!(existingBeanDef instanceof ConfigurationClassBeanDefinition)) {
|
||||
// no -> then it's an external override, probably XML
|
||||
|
||||
// overriding is legal, return immediately
|
||||
log.info(format("Skipping loading bean definition for %s: a definition for bean "
|
||||
+ "'%s' already exists. This is likely due to an override in XML.", method, beanName));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (method.getAnnotation(Primary.class) != null)
|
||||
beanDef.setPrimary(true);
|
||||
|
||||
// is this bean to be instantiated lazily?
|
||||
Lazy defaultLazy = configClass.getAnnotation(Lazy.class);
|
||||
if (defaultLazy != null)
|
||||
beanDef.setLazyInit(defaultLazy.value());
|
||||
Lazy lazy = method.getAnnotation(Lazy.class);
|
||||
if (lazy != null)
|
||||
beanDef.setLazyInit(lazy.value());
|
||||
|
||||
// does this bean have a custom init-method specified?
|
||||
String initMethodName = bean.initMethod();
|
||||
if (hasText(initMethodName))
|
||||
beanDef.setInitMethodName(initMethodName);
|
||||
|
||||
// does this bean have a custom destroy-method specified?
|
||||
String destroyMethodName = bean.destroyMethod();
|
||||
if (hasText(destroyMethodName))
|
||||
beanDef.setDestroyMethodName(destroyMethodName);
|
||||
|
||||
// is this method annotated with @Scope(scopedProxy=...)?
|
||||
if (scope != null && scope.proxyMode() != ScopedProxyMode.NO) {
|
||||
RootBeanDefinition targetDef = beanDef;
|
||||
|
||||
// Create a scoped proxy definition for the original bean name,
|
||||
// "hiding" the target bean in an internal target definition.
|
||||
String targetBeanName = resolveHiddenScopedProxyBeanName(beanName);
|
||||
RootBeanDefinition scopedProxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class);
|
||||
scopedProxyDefinition.getPropertyValues().addPropertyValue("targetBeanName", targetBeanName);
|
||||
|
||||
if (scope.proxyMode() == ScopedProxyMode.TARGET_CLASS)
|
||||
targetDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
|
||||
// ScopedFactoryBean's "proxyTargetClass" default is TRUE, so we
|
||||
// don't need to set it explicitly here.
|
||||
else
|
||||
scopedProxyDefinition.getPropertyValues().addPropertyValue("proxyTargetClass", Boolean.FALSE);
|
||||
|
||||
// The target bean should be ignored in favor of the scoped proxy.
|
||||
targetDef.setAutowireCandidate(false);
|
||||
|
||||
// Register the target bean as separate bean in the factory
|
||||
registry.registerBeanDefinition(targetBeanName, targetDef);
|
||||
|
||||
// replace the original bean definition with the target one
|
||||
beanDef = scopedProxyDefinition;
|
||||
}
|
||||
|
||||
if (bean.dependsOn().length > 0)
|
||||
beanDef.setDependsOn(bean.dependsOn());
|
||||
|
||||
log.info(format("Registering bean definition for @Bean method %s.%s()",
|
||||
configClass.getName(), beanName));
|
||||
|
||||
registry.registerBeanDefinition(beanName, beanDef);
|
||||
|
||||
}
|
||||
|
||||
private boolean containsBeanDefinitionIncludingAncestry(String beanName, BeanDefinitionRegistry registry) {
|
||||
try {
|
||||
getBeanDefinitionIncludingAncestry(beanName, registry);
|
||||
return true;
|
||||
} catch (NoSuchBeanDefinitionException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private BeanDefinition getBeanDefinitionIncludingAncestry(String beanName, BeanDefinitionRegistry registry) {
|
||||
if(!(registry instanceof ConfigurableListableBeanFactory))
|
||||
return registry.getBeanDefinition(beanName);
|
||||
|
||||
ConfigurableListableBeanFactory clbf = (ConfigurableListableBeanFactory) registry;
|
||||
|
||||
do {
|
||||
if (clbf.containsBeanDefinition(beanName))
|
||||
return registry.getBeanDefinition(beanName);
|
||||
|
||||
BeanFactory parent = clbf.getParentBeanFactory();
|
||||
if (parent == null) {
|
||||
clbf = null;
|
||||
} else if (parent instanceof ConfigurableListableBeanFactory) {
|
||||
clbf = (ConfigurableListableBeanFactory) parent;
|
||||
// TODO: re-enable
|
||||
// } else if (parent instanceof AbstractApplicationContext) {
|
||||
// clbf = ((AbstractApplicationContext) parent).getBeanFactory();
|
||||
} else {
|
||||
throw new IllegalStateException("unknown parent type: " + parent.getClass().getName());
|
||||
}
|
||||
} while (clbf != null);
|
||||
|
||||
throw new NoSuchBeanDefinitionException(
|
||||
format("No bean definition matching name '%s' " +
|
||||
"could be found in %s or its ancestry", beanName, registry));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the <i>hidden</i> name based on a scoped proxy bean name.
|
||||
*
|
||||
* @param originalBeanName the scope proxy bean name as declared in the
|
||||
* Configuration-annotated class
|
||||
*
|
||||
* @return the internally-used <i>hidden</i> bean name
|
||||
*/
|
||||
public static String resolveHiddenScopedProxyBeanName(String originalBeanName) {
|
||||
Assert.hasText(originalBeanName);
|
||||
return TARGET_NAME_PREFIX.concat(originalBeanName);
|
||||
}
|
||||
|
||||
/** Prefix used when registering the target object for a scoped proxy. */
|
||||
private static final String TARGET_NAME_PREFIX = "scopedTarget.";
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* {@link RootBeanDefinition} marker subclass used to signify that a bean definition created
|
||||
* by JavaConfig as opposed to any other configuration source. Used in bean overriding cases
|
||||
* where it's necessary to determine whether the bean definition was created externally
|
||||
* (e.g. via XML).
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
class ConfigurationClassBeanDefinition extends RootBeanDefinition {
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import java.lang.annotation.Target;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Documented;
|
||||
|
||||
/**
|
||||
* Beans on which the current bean depends. Any beans specified are guaranteed to be
|
||||
* created by the container before this bean. Used infrequently in cases where a bean
|
||||
* does not explicitly depend on another through properties or constructor arguments,
|
||||
* but rather depends on the side effects of another bean's initialization.
|
||||
* <p>Note: This attribute will not be inherited by child bean definitions,
|
||||
* hence it needs to be specified per concrete bean definition.
|
||||
*
|
||||
* <p>May be used on any class directly or indirectly annotated with
|
||||
* {@link org.springframework.stereotype.Component} or on methods annotated
|
||||
* with {@link Bean}.
|
||||
*
|
||||
* <p>Using {@link DependsOn} at the class level has no effect unless component-scanning
|
||||
* is being used. If a {@link DependsOn}-annotated class is declared via XML,
|
||||
* {@link DependsOn} annotation metadata is ignored, and
|
||||
* {@literal <bean depends-on="..."/>} is respected instead.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 3.0
|
||||
*/
|
||||
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
public @interface DependsOn {
|
||||
|
||||
String[] value() default {};
|
||||
|
||||
}
|
||||
@@ -23,18 +23,18 @@ import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
|
||||
/**
|
||||
* Annotation that allows one {@link Configuration} class to import another Configuration,
|
||||
* and thereby all its {@link Bean} definitions.
|
||||
*
|
||||
* <p>Provides functionality equivalent to the {@literal <import/>} element in Spring XML.
|
||||
* Only supported for actual {@link Configuration} classes.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @since 3.0
|
||||
* @see Configuration
|
||||
*/
|
||||
@Target({ ElementType.TYPE })
|
||||
@Target({ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
import static org.springframework.context.annotation.AsmUtils.*;
|
||||
import static org.springframework.util.ClassUtils.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.springframework.asm.AnnotationVisitor;
|
||||
import org.springframework.asm.ClassReader;
|
||||
import org.springframework.asm.Type;
|
||||
import org.springframework.beans.factory.parsing.ProblemReporter;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
/**
|
||||
* ASM {@link AnnotationVisitor} implementation that reads an {@link Import} annotation
|
||||
* for all its specified classes and then one by one processes each class with a new
|
||||
* {@link ConfigurationClassVisitor}.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see Import
|
||||
* @see ImportStack
|
||||
* @see ImportStackHolder
|
||||
* @see ConfigurationClassVisitor
|
||||
*/
|
||||
class ImportAnnotationVisitor extends AnnotationAdapter {
|
||||
|
||||
private final ArrayList<String> classesToImport = new ArrayList<String>();
|
||||
private final ConfigurationModel model;
|
||||
private final ProblemReporter problemReporter;
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
public ImportAnnotationVisitor(ConfigurationModel model, ProblemReporter problemReporter, ClassLoader classLoader) {
|
||||
super(ASM_EMPTY_VISITOR);
|
||||
this.model = model;
|
||||
this.problemReporter = problemReporter;
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnnotationVisitor visitArray(String attribName) {
|
||||
Assert.isTrue("value".equals(attribName),
|
||||
format("expected 'value' attribute, got unknown '%s' attribute", attribName));
|
||||
|
||||
return new AnnotationAdapter(ASM_EMPTY_VISITOR) {
|
||||
@Override
|
||||
public void visit(String na, Object type) {
|
||||
Assert.isInstanceOf(Type.class, type);
|
||||
classesToImport.add(((Type) type).getClassName());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitEnd() {
|
||||
for (String classToImport : classesToImport)
|
||||
processClassToImport(classToImport);
|
||||
|
||||
ImportStackHolder.getImportStack().pop();
|
||||
}
|
||||
|
||||
private void processClassToImport(String classToImport) {
|
||||
ConfigurationClass configClass = new ConfigurationClass();
|
||||
|
||||
ClassReader reader = newAsmClassReader(convertClassNameToResourcePath(classToImport), classLoader);
|
||||
|
||||
reader.accept(new ConfigurationClassVisitor(configClass, model, problemReporter, classLoader), false);
|
||||
|
||||
model.add(configClass);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.Stack;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
/**
|
||||
* {@link Stack} used for detecting circular use of the {@link Import} annotation.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see Import
|
||||
* @see ImportStackHolder
|
||||
* @see CircularImportException
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
class ImportStack extends Stack<ConfigurationClass> {
|
||||
|
||||
/**
|
||||
* Simplified contains() implementation that tests to see if any {@link ConfigurationClass}
|
||||
* exists within this stack that has the same name as <var>elem</var>. Elem must be of
|
||||
* type ConfigurationClass.
|
||||
*/
|
||||
@Override
|
||||
public boolean contains(Object elem) {
|
||||
Assert.isInstanceOf(ConfigurationClass.class, elem);
|
||||
|
||||
ConfigurationClass configClass = (ConfigurationClass) elem;
|
||||
|
||||
Comparator<ConfigurationClass> comparator = new Comparator<ConfigurationClass>() {
|
||||
public int compare(ConfigurationClass first, ConfigurationClass second) {
|
||||
return first.getName().equals(second.getName()) ? 0 : 1;
|
||||
}
|
||||
};
|
||||
|
||||
int index = Collections.binarySearch(this, configClass, comparator);
|
||||
|
||||
return index >= 0 ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a stack containing (in order)
|
||||
* <ol>
|
||||
* <li>com.acme.Foo</li>
|
||||
* <li>com.acme.Bar</li>
|
||||
* <li>com.acme.Baz</li>
|
||||
* </ol>
|
||||
* Returns "Foo->Bar->Baz". In the case of an empty stack, returns empty string.
|
||||
*/
|
||||
@Override
|
||||
public synchronized String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
Iterator<ConfigurationClass> iterator = this.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
builder.append(iterator.next().getSimpleName());
|
||||
if (iterator.hasNext())
|
||||
builder.append("->");
|
||||
}
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Holder class to expose a thread-bound {@link ImportStack}, used while detecting circular
|
||||
* declarations of the {@link Import} annotation.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see Import
|
||||
* @see ImportStack
|
||||
* @see CircularImportException
|
||||
*/
|
||||
class ImportStackHolder {
|
||||
|
||||
private static ThreadLocal<ImportStack> stackHolder = new ThreadLocal<ImportStack>() {
|
||||
@Override
|
||||
protected ImportStack initialValue() {
|
||||
return new ImportStack();
|
||||
}
|
||||
};
|
||||
|
||||
public static ImportStack getImportStack() {
|
||||
return stackHolder.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Holder for circular @Import detection stack";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,7 +21,7 @@ import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import java.lang.annotation.Inherited;
|
||||
|
||||
/**
|
||||
* Indicates whether a bean is to be lazily initialized.
|
||||
@@ -51,8 +51,9 @@ import java.lang.annotation.Target;
|
||||
* @see Configuration
|
||||
* @see org.springframework.stereotype.Component
|
||||
*/
|
||||
@Target({ ElementType.TYPE, ElementType.METHOD })
|
||||
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
public @interface Lazy {
|
||||
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static org.springframework.util.ClassUtils.*;
|
||||
|
||||
import org.springframework.beans.BeanMetadataElement;
|
||||
import org.springframework.beans.factory.parsing.Location;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Represents a class, free from java reflection,
|
||||
* populated by {@link ConfigurationClassParser}.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see ConfigurationModel
|
||||
* @see ConfigurationClass
|
||||
* @see ConfigurationClassParser
|
||||
*/
|
||||
class ModelClass implements BeanMetadataElement {
|
||||
|
||||
private String name;
|
||||
private boolean isInterface;
|
||||
private transient Object source;
|
||||
|
||||
/**
|
||||
* Creates a new and empty ModelClass instance.
|
||||
*/
|
||||
public ModelClass() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ModelClass instance
|
||||
*
|
||||
* @param name fully-qualified name of the class being represented
|
||||
*/
|
||||
public ModelClass(String name) {
|
||||
this(name, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ModelClass instance
|
||||
*
|
||||
* @param name fully-qualified name of the class being represented
|
||||
* @param isInterface whether the represented type is an interface
|
||||
*/
|
||||
public ModelClass(String name, boolean isInterface) {
|
||||
this.name = name;
|
||||
this.isInterface = isInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fully-qualified name of this class.
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the fully-qualified name of this class.
|
||||
*/
|
||||
public void setName(String className) {
|
||||
this.name = className;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the non-qualified name of this class. Given com.acme.Foo, returns 'Foo'.
|
||||
*/
|
||||
public String getSimpleName() {
|
||||
return name == null ? null : ClassUtils.getShortName(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the class represented by this ModelClass instance is an interface.
|
||||
*/
|
||||
public boolean isInterface() {
|
||||
return isInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Signifies that this class is (true) or is not (false) an interface.
|
||||
*/
|
||||
public void setInterface(boolean isInterface) {
|
||||
this.isInterface = isInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a resource path-formatted representation of the .java file that declares this
|
||||
* class
|
||||
*/
|
||||
public Object getSource() {
|
||||
return source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the source location for this class. Must be a resource-path formatted string.
|
||||
*
|
||||
* @param source resource path to the .java file that declares this class.
|
||||
*/
|
||||
public void setSource(Object source) {
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
public Location getLocation() {
|
||||
if(getName() == null)
|
||||
throw new IllegalStateException("'name' property is null. Call setName() before calling getLocation()");
|
||||
return new Location(new ClassPathResource(convertClassNameToResourcePath(getName())), getSource());
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a ModelClass instance representing a class com.acme.Foo, this method will
|
||||
* return
|
||||
*
|
||||
* <pre>
|
||||
* ModelClass: name=Foo
|
||||
* </pre>
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s: name=%s", getClass().getSimpleName(), getSimpleName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = (prime * result) + (isInterface ? 1231 : 1237);
|
||||
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
|
||||
if (obj == null)
|
||||
return false;
|
||||
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
|
||||
ModelClass other = (ModelClass) obj;
|
||||
if (isInterface != other.isInterface)
|
||||
return false;
|
||||
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static org.springframework.context.annotation.AsmUtils.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.springframework.asm.AnnotationVisitor;
|
||||
|
||||
|
||||
/**
|
||||
* ASM {@link AnnotationVisitor} that visits any annotation array values while populating
|
||||
* a new {@link MutableAnnotation} instance.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see MutableAnnotation
|
||||
* @see AsmUtils#createMutableAnnotation
|
||||
*/
|
||||
class MutableAnnotationArrayVisitor extends AnnotationAdapter {
|
||||
|
||||
private final ArrayList<Object> values = new ArrayList<Object>();
|
||||
private final MutableAnnotation mutableAnno;
|
||||
private final String attribName;
|
||||
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
public MutableAnnotationArrayVisitor(MutableAnnotation mutableAnno, String attribName, ClassLoader classLoader) {
|
||||
super(AsmUtils.ASM_EMPTY_VISITOR);
|
||||
|
||||
this.mutableAnno = mutableAnno;
|
||||
this.attribName = attribName;
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(String na, Object value) {
|
||||
values.add(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnnotationVisitor visitAnnotation(String na, String annoTypeDesc) {
|
||||
String annoTypeName = convertAsmTypeDescriptorToClassName(annoTypeDesc);
|
||||
Class<? extends Annotation> annoType = loadToolingSafeClass(annoTypeName, classLoader);
|
||||
|
||||
if (annoType == null)
|
||||
return super.visitAnnotation(na, annoTypeDesc);
|
||||
|
||||
Annotation anno = createMutableAnnotation(annoType, classLoader);
|
||||
values.add(anno);
|
||||
return new MutableAnnotationVisitor(anno, classLoader);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitEnd() {
|
||||
Class<?> arrayType = mutableAnno.getAttributeType(attribName);
|
||||
Object[] array = (Object[]) Array.newInstance(arrayType.getComponentType(), 0);
|
||||
mutableAnno.setAttributeValue(attribName, values.toArray(array));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static java.lang.String.*;
|
||||
import static org.springframework.core.annotation.AnnotationUtils.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Handles calls to {@link MutableAnnotation} attribute methods at runtime. Essentially
|
||||
* emulates what JDK annotation dynamic proxies do.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see MutableAnnotation
|
||||
* @see AsmUtils#createMutableAnnotation
|
||||
*/
|
||||
final class MutableAnnotationInvocationHandler implements InvocationHandler {
|
||||
|
||||
private final Class<? extends Annotation> annoType;
|
||||
private final HashMap<String, Object> attributes = new HashMap<String, Object>();
|
||||
private final HashMap<String, Class<?>> attributeTypes = new HashMap<String, Class<?>>();
|
||||
|
||||
public MutableAnnotationInvocationHandler(Class<? extends Annotation> annoType) {
|
||||
// pre-populate the attributes hash will all the names
|
||||
// and default values of the attributes defined in 'annoType'
|
||||
Method[] attribs = annoType.getDeclaredMethods();
|
||||
for (Method attrib : attribs) {
|
||||
this.attributes.put(attrib.getName(), getDefaultValue(annoType, attrib.getName()));
|
||||
this.attributeTypes.put(attrib.getName(), getAttributeType(annoType, attrib.getName()));
|
||||
}
|
||||
|
||||
this.annoType = annoType;
|
||||
}
|
||||
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
Assert.isInstanceOf(Annotation.class, proxy);
|
||||
|
||||
String methodName = method.getName();
|
||||
|
||||
// first -> check to see if this method is an attribute on our annotation
|
||||
if (attributes.containsKey(methodName))
|
||||
return attributes.get(methodName);
|
||||
|
||||
|
||||
// second -> is it a method from java.lang.annotation.Annotation?
|
||||
if (methodName.equals("annotationType"))
|
||||
return annoType;
|
||||
|
||||
|
||||
// third -> is it a method from java.lang.Object?
|
||||
if (methodName.equals("toString"))
|
||||
return format("@%s(%s)", annoType.getName(), getAttribs());
|
||||
|
||||
if (methodName.equals("equals"))
|
||||
return isEqualTo(proxy, args[0]);
|
||||
|
||||
if (methodName.equals("hashCode"))
|
||||
return calculateHashCode(proxy);
|
||||
|
||||
|
||||
// finally -> is it a method specified by MutableAnno?
|
||||
if (methodName.equals("setAttributeValue")) {
|
||||
attributes.put((String) args[0], args[1]);
|
||||
return null; // setAttributeValue has a 'void' return type
|
||||
}
|
||||
|
||||
if (methodName.equals("getAttributeType"))
|
||||
return attributeTypes.get(args[0]);
|
||||
|
||||
throw new UnsupportedOperationException("this proxy does not support method: " + methodName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Conforms to the hashCode() specification for Annotation.
|
||||
*
|
||||
* @see Annotation#hashCode()
|
||||
*/
|
||||
private Object calculateHashCode(Object proxy) {
|
||||
int sum = 0;
|
||||
|
||||
for (String attribName : attributes.keySet()) {
|
||||
Object attribValue = attributes.get(attribName);
|
||||
|
||||
final int attribNameHashCode = attribName.hashCode();
|
||||
final int attribValueHashCode;
|
||||
|
||||
if (attribValue == null)
|
||||
// memberValue may be null when a mutable annotation is being added to a
|
||||
// collection
|
||||
// and before it has actually been visited (and populated) by
|
||||
// MutableAnnotationVisitor
|
||||
attribValueHashCode = 0;
|
||||
else if (attribValue.getClass().isArray())
|
||||
attribValueHashCode = Arrays.hashCode((Object[]) attribValue);
|
||||
else
|
||||
attribValueHashCode = attribValue.hashCode();
|
||||
|
||||
sum += (127 * attribNameHashCode) ^ attribValueHashCode;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares <var>proxy</var> object and <var>other</var> object by comparing the return
|
||||
* values of the methods specified by their common {@link Annotation} ancestry.
|
||||
* <p/>
|
||||
* <var>other</var> must be the same type as or a subtype of <var>proxy</var>. Will
|
||||
* return false otherwise.
|
||||
* <p/>
|
||||
* Eagerly returns true if {@code proxy} == <var>other</var>
|
||||
* </p>
|
||||
* <p/>
|
||||
* Conforms strictly to the equals() specification for Annotation
|
||||
* </p>
|
||||
*
|
||||
* @see Annotation#equals(Object)
|
||||
*/
|
||||
private Object isEqualTo(Object proxy, Object other) {
|
||||
if (proxy == other)
|
||||
return true;
|
||||
|
||||
if (other == null)
|
||||
return false;
|
||||
|
||||
if (!annoType.isAssignableFrom(other.getClass()))
|
||||
return false;
|
||||
|
||||
for (String attribName : attributes.keySet()) {
|
||||
Object thisVal;
|
||||
Object thatVal;
|
||||
|
||||
try {
|
||||
thisVal = attributes.get(attribName);
|
||||
thatVal = other.getClass().getDeclaredMethod(attribName).invoke(other);
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
|
||||
if ((thisVal == null) && (thatVal != null))
|
||||
return false;
|
||||
|
||||
if ((thatVal == null) && (thisVal != null))
|
||||
return false;
|
||||
|
||||
if (thatVal.getClass().isArray()) {
|
||||
if (!Arrays.equals((Object[]) thatVal, (Object[]) thisVal)) {
|
||||
return false;
|
||||
}
|
||||
} else if (thisVal instanceof Double) {
|
||||
if (!Double.valueOf((Double) thisVal).equals(Double.valueOf((Double) thatVal)))
|
||||
return false;
|
||||
} else if (thisVal instanceof Float) {
|
||||
if (!Float.valueOf((Float) thisVal).equals(Float.valueOf((Float) thatVal)))
|
||||
return false;
|
||||
} else if (!thisVal.equals(thatVal)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private String getAttribs() {
|
||||
ArrayList<String> attribs = new ArrayList<String>();
|
||||
|
||||
for (String attribName : attributes.keySet())
|
||||
attribs.add(format("%s=%s", attribName, attributes.get(attribName)));
|
||||
|
||||
return StringUtils.collectionToDelimitedString(attribs, ", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the type of the given annotation attribute.
|
||||
*/
|
||||
private static Class<?> getAttributeType(Class<? extends Annotation> annotationType, String attributeName) {
|
||||
Method method = null;
|
||||
|
||||
try {
|
||||
method = annotationType.getDeclaredMethod(attributeName);
|
||||
} catch (Exception ex) {
|
||||
ReflectionUtils.handleReflectionException(ex);
|
||||
}
|
||||
|
||||
return method.getReturnType();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.context.annotation;
|
||||
|
||||
import static org.springframework.context.annotation.AsmUtils.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.springframework.asm.AnnotationVisitor;
|
||||
import org.springframework.asm.Type;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
/**
|
||||
* ASM {@link AnnotationVisitor} that populates a given {@link MutableAnnotation} instance
|
||||
* with its attributes.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @see MutableAnnotation
|
||||
* @see MutableAnnotationInvocationHandler
|
||||
* @see AsmUtils#createMutableAnnotation
|
||||
*/
|
||||
class MutableAnnotationVisitor implements AnnotationVisitor {
|
||||
|
||||
protected final MutableAnnotation mutableAnno;
|
||||
|
||||
private final ClassLoader classLoader;
|
||||
|
||||
/**
|
||||
* Creates a new {@link MutableAnnotationVisitor} instance that will populate the the
|
||||
* attributes of the given <var>mutableAnno</var>. Accepts {@link Annotation} instead of
|
||||
* {@link MutableAnnotation} to avoid the need for callers to typecast.
|
||||
*
|
||||
* @param mutableAnno {@link MutableAnnotation} instance to visit and populate
|
||||
*
|
||||
* @throws IllegalArgumentException if <var>mutableAnno</var> is not of type
|
||||
* {@link MutableAnnotation}
|
||||
*
|
||||
* @see AsmUtils#createMutableAnnotation
|
||||
*/
|
||||
public MutableAnnotationVisitor(Annotation mutableAnno, ClassLoader classLoader) {
|
||||
Assert.isInstanceOf(MutableAnnotation.class, mutableAnno, "annotation must be mutable");
|
||||
this.mutableAnno = (MutableAnnotation) mutableAnno;
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitArray(final String attribName) {
|
||||
return new MutableAnnotationArrayVisitor(mutableAnno, attribName, classLoader);
|
||||
}
|
||||
|
||||
public void visit(String attribName, Object attribValue) {
|
||||
Class<?> attribReturnType = mutableAnno.getAttributeType(attribName);
|
||||
|
||||
if (attribReturnType.equals(Class.class)) {
|
||||
// the attribute type is Class -> load it and set it.
|
||||
String fqClassName = ((Type) attribValue).getClassName();
|
||||
|
||||
Class<?> classVal = loadToolingSafeClass(fqClassName, classLoader);
|
||||
|
||||
if (classVal == null)
|
||||
return;
|
||||
|
||||
mutableAnno.setAttributeValue(attribName, classVal);
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise, assume the value can be set literally
|
||||
mutableAnno.setAttributeValue(attribName, attribValue);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void visitEnum(String attribName, String enumTypeDescriptor, String strEnumValue) {
|
||||
String enumClassName = convertAsmTypeDescriptorToClassName(enumTypeDescriptor);
|
||||
|
||||
Class<? extends Enum> enumClass = loadToolingSafeClass(enumClassName, classLoader);
|
||||
|
||||
if (enumClass == null)
|
||||
return;
|
||||
|
||||
Enum enumValue = Enum.valueOf(enumClass, strEnumValue);
|
||||
mutableAnno.setAttributeValue(attribName, enumValue);
|
||||
}
|
||||
|
||||
public AnnotationVisitor visitAnnotation(String attribName, String attribAnnoTypeDesc) {
|
||||
String annoTypeName = convertAsmTypeDescriptorToClassName(attribAnnoTypeDesc);
|
||||
Class<? extends Annotation> annoType = loadToolingSafeClass(annoTypeName, classLoader);
|
||||
|
||||
if (annoType == null)
|
||||
return ASM_EMPTY_VISITOR.visitAnnotation(attribName, attribAnnoTypeDesc);
|
||||
|
||||
Annotation anno = createMutableAnnotation(annoType, classLoader);
|
||||
|
||||
try {
|
||||
Field attribute = mutableAnno.getClass().getField(attribName);
|
||||
attribute.set(mutableAnno, anno);
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
|
||||
return new MutableAnnotationVisitor(anno, classLoader);
|
||||
}
|
||||
|
||||
public void visitEnd() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -18,11 +18,11 @@ package org.springframework.context.annotation;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
|
||||
/**
|
||||
* Indicates that a bean should be given preference when multiple candidates
|
||||
* are qualified to autowire a single-valued dependency. If exactly one 'primary'
|
||||
@@ -43,8 +43,9 @@ import java.lang.annotation.Target;
|
||||
* @see Bean
|
||||
* @see org.springframework.stereotype.Component
|
||||
*/
|
||||
@Target({ ElementType.TYPE, ElementType.METHOD })
|
||||
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
@Documented
|
||||
public @interface Primary {
|
||||
|
||||
|
||||
@@ -59,13 +59,11 @@ public @interface Scope {
|
||||
/**
|
||||
* Specifies whether a component should be configured as a scoped proxy
|
||||
* and if so, whether the proxy should be interface-based or subclass-based.
|
||||
*
|
||||
* <p>Defaults to {@link ScopedProxyMode#NO}, indicating no scoped proxy
|
||||
* should be created.
|
||||
*
|
||||
* <p>Analogous to {@literal <aop:scoped-proxy/>} support in Spring XML. Valid
|
||||
* only in conjunction with a non-singleton, non-prototype {@link #value()}.
|
||||
*/
|
||||
ScopedProxyMode proxyMode() default ScopedProxyMode.NO;
|
||||
ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
|
||||
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Describes scope characteristics for a Spring-managed bean including the scope
|
||||
@@ -26,6 +27,7 @@ import org.springframework.beans.factory.config.BeanDefinition;
|
||||
* scoped-proxies.
|
||||
*
|
||||
* @author Mark Fisher
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.5
|
||||
* @see ScopeMetadataResolver
|
||||
* @see ScopedProxyMode
|
||||
@@ -41,6 +43,7 @@ public class ScopeMetadata {
|
||||
* Set the name of the scope.
|
||||
*/
|
||||
public void setScopeName(String scopeName) {
|
||||
Assert.notNull(scopeName, "'scopeName' must not be null");
|
||||
this.scopeName = scopeName;
|
||||
}
|
||||
|
||||
@@ -55,6 +58,7 @@ public class ScopeMetadata {
|
||||
* Set the proxy-mode to be applied to the scoped instance.
|
||||
*/
|
||||
public void setScopedProxyMode(ScopedProxyMode scopedProxyMode) {
|
||||
Assert.notNull(scopedProxyMode, "'scopedProxyMode' must not be null");
|
||||
this.scopedProxyMode = scopedProxyMode;
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ import org.springframework.beans.factory.config.BeanDefinition;
|
||||
*
|
||||
* @author Mark Fisher
|
||||
* @since 2.5
|
||||
* @see Scope
|
||||
* @see org.springframework.context.annotation.Scope
|
||||
*/
|
||||
public interface ScopeMetadataResolver {
|
||||
|
||||
|
||||
@@ -29,6 +29,12 @@ package org.springframework.context.annotation;
|
||||
*/
|
||||
public enum ScopedProxyMode {
|
||||
|
||||
/**
|
||||
* Default typically equals {@link #NO}, unless a different default
|
||||
* has been configured at the component-scan instruction level.
|
||||
*/
|
||||
DEFAULT,
|
||||
|
||||
/**
|
||||
* Do not create a scoped proxy.
|
||||
* <p>This proxy-mode is not typically useful when used with a
|
||||
|
||||
@@ -16,17 +16,16 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
|
||||
/**
|
||||
* Enumerates the names of the scopes supported out of the box in Spring.
|
||||
*
|
||||
*
|
||||
* <p>Not modeled as an actual java enum because annotations that accept a scope attribute
|
||||
* must allow for user-defined scope names. Given that java enums are not extensible, these
|
||||
* must remain simple string constants.
|
||||
*
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @since 3.0
|
||||
* @see Scope
|
||||
* @see org.springframework.context.annotation.Scope
|
||||
*/
|
||||
public class StandardScopes {
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.beans.support.ResourceEditorRegistrar;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
@@ -487,9 +488,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
|
||||
*/
|
||||
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
|
||||
// Invoke factory processors registered with the context instance.
|
||||
for (BeanFactoryPostProcessor factoryProcessor : getBeanFactoryPostProcessors()) {
|
||||
factoryProcessor.postProcessBeanFactory(beanFactory);
|
||||
}
|
||||
invokeBeanFactoryPostProcessors(getBeanFactoryPostProcessors(), beanFactory);
|
||||
|
||||
// Do not initialize FactoryBeans here: We need to leave all regular beans
|
||||
// uninitialized to let the bean factory post-processors apply to them!
|
||||
@@ -515,7 +514,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
|
||||
|
||||
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
|
||||
OrderComparator.sort(priorityOrderedPostProcessors);
|
||||
invokeBeanFactoryPostProcessors(beanFactory, priorityOrderedPostProcessors);
|
||||
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
|
||||
|
||||
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
|
||||
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
|
||||
@@ -523,21 +522,21 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
|
||||
orderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
|
||||
}
|
||||
OrderComparator.sort(orderedPostProcessors);
|
||||
invokeBeanFactoryPostProcessors(beanFactory, orderedPostProcessors);
|
||||
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
|
||||
|
||||
// Finally, invoke all other BeanFactoryPostProcessors.
|
||||
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
|
||||
for (String postProcessorName : nonOrderedPostProcessorNames) {
|
||||
nonOrderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
|
||||
}
|
||||
invokeBeanFactoryPostProcessors(beanFactory, nonOrderedPostProcessors);
|
||||
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke the given BeanFactoryPostProcessor beans.
|
||||
*/
|
||||
private void invokeBeanFactoryPostProcessors(
|
||||
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> postProcessors) {
|
||||
List<BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
|
||||
|
||||
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
|
||||
postProcessor.postProcessBeanFactory(beanFactory);
|
||||
|
||||
Reference in New Issue
Block a user