Polishing

(cherry picked from commit 162ee36)
This commit is contained in:
Juergen Hoeller
2015-03-21 00:35:08 +01:00
parent 2de5faf56c
commit 8d14e7736a
14 changed files with 129 additions and 141 deletions

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -114,6 +114,7 @@ public interface BeanFactory {
*/ */
String FACTORY_BEAN_PREFIX = "&"; String FACTORY_BEAN_PREFIX = "&";
/** /**
* Return an instance, which may be shared or independent, of the specified bean. * Return an instance, which may be shared or independent, of the specified bean.
* <p>This method allows a Spring BeanFactory to be used as a replacement for the * <p>This method allows a Spring BeanFactory to be used as a replacement for the
@@ -202,6 +203,7 @@ public interface BeanFactory {
*/ */
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException; <T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
/** /**
* Does this bean factory contain a bean definition or externally registered singleton * Does this bean factory contain a bean definition or externally registered singleton
* instance with the given name? * instance with the given name?

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.beans.factory; package org.springframework.beans.factory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;

View File

@@ -323,7 +323,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
//--------------------------------------------------------------------- //---------------------------------------------------------------------
// Implementation of ListableBeanFactory interface // Implementation of remaining BeanFactory methods
//--------------------------------------------------------------------- //---------------------------------------------------------------------
@Override @Override

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,8 +23,6 @@ import java.util.Map;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
@@ -53,16 +51,16 @@ public final class BeanFactoryUtilsTests {
private static final Resource LEAF_CONTEXT = qualifiedResource(CLASS, "leaf.xml"); private static final Resource LEAF_CONTEXT = qualifiedResource(CLASS, "leaf.xml");
private static final Resource DEPENDENT_BEANS_CONTEXT = qualifiedResource(CLASS, "dependentBeans.xml"); private static final Resource DEPENDENT_BEANS_CONTEXT = qualifiedResource(CLASS, "dependentBeans.xml");
private ConfigurableListableBeanFactory listableBeanFactory; private DefaultListableBeanFactory listableBeanFactory;
private DefaultListableBeanFactory dependentBeansFactory;
private ConfigurableListableBeanFactory dependentBeansBF;
@Before @Before
public void setUp() { public void setUp() {
// Interesting hierarchical factory to test counts. // Interesting hierarchical factory to test counts.
// Slow to read so we cache it. // Slow to read so we cache it.
DefaultListableBeanFactory grandParent = new DefaultListableBeanFactory(); DefaultListableBeanFactory grandParent = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(grandParent).loadBeanDefinitions(ROOT_CONTEXT); new XmlBeanDefinitionReader(grandParent).loadBeanDefinitions(ROOT_CONTEXT);
DefaultListableBeanFactory parent = new DefaultListableBeanFactory(grandParent); DefaultListableBeanFactory parent = new DefaultListableBeanFactory(grandParent);
@@ -70,12 +68,13 @@ public final class BeanFactoryUtilsTests {
DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
new XmlBeanDefinitionReader(child).loadBeanDefinitions(LEAF_CONTEXT); new XmlBeanDefinitionReader(child).loadBeanDefinitions(LEAF_CONTEXT);
this.dependentBeansBF = new DefaultListableBeanFactory(); this.dependentBeansFactory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader((BeanDefinitionRegistry) this.dependentBeansBF).loadBeanDefinitions(DEPENDENT_BEANS_CONTEXT); new XmlBeanDefinitionReader(this.dependentBeansFactory).loadBeanDefinitions(DEPENDENT_BEANS_CONTEXT);
dependentBeansBF.preInstantiateSingletons(); dependentBeansFactory.preInstantiateSingletons();
this.listableBeanFactory = child; this.listableBeanFactory = child;
} }
@Test @Test
public void testHierarchicalCountBeansWithNonHierarchicalFactory() { public void testHierarchicalCountBeansWithNonHierarchicalFactory() {
StaticListableBeanFactory lbf = new StaticListableBeanFactory(); StaticListableBeanFactory lbf = new StaticListableBeanFactory();
@@ -92,22 +91,21 @@ public final class BeanFactoryUtilsTests {
// Leaf count // Leaf count
assertTrue(this.listableBeanFactory.getBeanDefinitionCount() == 1); assertTrue(this.listableBeanFactory.getBeanDefinitionCount() == 1);
// Count minus duplicate // Count minus duplicate
assertTrue("Should count 7 beans, not " assertTrue("Should count 7 beans, not " + BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory),
+ BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory), BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory) == 7);
BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory) == 7);
} }
@Test @Test
public void testHierarchicalNamesWithNoMatch() throws Exception { public void testHierarchicalNamesWithNoMatch() throws Exception {
List<String> names = Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, List<String> names = Arrays.asList(
NoOp.class)); BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, NoOp.class));
assertEquals(0, names.size()); assertEquals(0, names.size());
} }
@Test @Test
public void testHierarchicalNamesWithMatchOnlyInRoot() throws Exception { public void testHierarchicalNamesWithMatchOnlyInRoot() throws Exception {
List<String> names = Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, List<String> names = Arrays.asList(
IndexedTestBean.class)); BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, IndexedTestBean.class));
assertEquals(1, names.size()); assertEquals(1, names.size());
assertTrue(names.contains("indexedBean")); assertTrue(names.contains("indexedBean"));
// Distinguish from default ListableBeanFactory behavior // Distinguish from default ListableBeanFactory behavior
@@ -116,8 +114,8 @@ public final class BeanFactoryUtilsTests {
@Test @Test
public void testGetBeanNamesForTypeWithOverride() throws Exception { public void testGetBeanNamesForTypeWithOverride() throws Exception {
List<String> names = Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, List<String> names = Arrays.asList(
ITestBean.class)); BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class));
// includes 2 TestBeans from FactoryBeans (DummyFactory definitions) // includes 2 TestBeans from FactoryBeans (DummyFactory definitions)
assertEquals(4, names.size()); assertEquals(4, names.size());
assertTrue(names.contains("test")); assertTrue(names.contains("test"));
@@ -130,7 +128,7 @@ public final class BeanFactoryUtilsTests {
public void testNoBeansOfType() { public void testNoBeansOfType() {
StaticListableBeanFactory lbf = new StaticListableBeanFactory(); StaticListableBeanFactory lbf = new StaticListableBeanFactory();
lbf.addBean("foo", new Object()); lbf.addBean("foo", new Object());
Map<?, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, false); Map<String, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, false);
assertTrue(beans.isEmpty()); assertTrue(beans.isEmpty());
} }
@@ -147,7 +145,7 @@ public final class BeanFactoryUtilsTests {
lbf.addBean("t3", t3); lbf.addBean("t3", t3);
lbf.addBean("t4", t4); lbf.addBean("t4", t4);
Map<?, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, false); Map<String, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, false);
assertEquals(2, beans.size()); assertEquals(2, beans.size());
assertEquals(t1, beans.get("t1")); assertEquals(t1, beans.get("t1"));
assertEquals(t2, beans.get("t2")); assertEquals(t2, beans.get("t2"));
@@ -191,8 +189,8 @@ public final class BeanFactoryUtilsTests {
this.listableBeanFactory.registerSingleton("t3", t3); this.listableBeanFactory.registerSingleton("t3", t3);
this.listableBeanFactory.registerSingleton("t4", t4); this.listableBeanFactory.registerSingleton("t4", t4);
Map<?, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, Map<String, ?> beans =
false); BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, false);
assertEquals(6, beans.size()); assertEquals(6, beans.size());
assertEquals(test3, beans.get("test3")); assertEquals(test3, beans.get("test3"));
assertEquals(test, beans.get("test")); assertEquals(test, beans.get("test"));
@@ -200,12 +198,9 @@ public final class BeanFactoryUtilsTests {
assertEquals(t2, beans.get("t2")); assertEquals(t2, beans.get("t2"));
assertEquals(t3.getObject(), beans.get("t3")); assertEquals(t3.getObject(), beans.get("t3"));
assertTrue(beans.get("t4") instanceof TestBean); assertTrue(beans.get("t4") instanceof TestBean);
// t3 and t4 are found here as of Spring 2.0, since they are // t3 and t4 are found here as of Spring 2.0, since they are pre-registered
// pre-registered // singleton instances, while testFactory1 and testFactory are *not* found
// singleton instances, while testFactory1 and testFactory are *not* // because they are FactoryBean definitions that haven't been initialized yet.
// found
// because they are FactoryBean definitions that haven't been
// initialized yet.
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true);
Object testFactory1 = this.listableBeanFactory.getBean("testFactory1"); Object testFactory1 = this.listableBeanFactory.getBean("testFactory1");
@@ -247,8 +242,8 @@ public final class BeanFactoryUtilsTests {
Object test3 = this.listableBeanFactory.getBean("test3"); Object test3 = this.listableBeanFactory.getBean("test3");
Object test = this.listableBeanFactory.getBean("test"); Object test = this.listableBeanFactory.getBean("test");
Map<?, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, Map<String, ?> beans =
false); BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, false);
assertEquals(2, beans.size()); assertEquals(2, beans.size());
assertEquals(test3, beans.get("test3")); assertEquals(test3, beans.get("test3"));
assertEquals(test, beans.get("test")); assertEquals(test, beans.get("test"));
@@ -283,25 +278,25 @@ public final class BeanFactoryUtilsTests {
@Test @Test
public void testADependencies() { public void testADependencies() {
String[] deps = this.dependentBeansBF.getDependentBeans("a"); String[] deps = this.dependentBeansFactory.getDependentBeans("a");
assertTrue(ObjectUtils.isEmpty(deps)); assertTrue(ObjectUtils.isEmpty(deps));
} }
@Test @Test
public void testBDependencies() { public void testBDependencies() {
String[] deps = this.dependentBeansBF.getDependentBeans("b"); String[] deps = this.dependentBeansFactory.getDependentBeans("b");
assertTrue(Arrays.equals(new String[] { "c" }, deps)); assertTrue(Arrays.equals(new String[] { "c" }, deps));
} }
@Test @Test
public void testCDependencies() { public void testCDependencies() {
String[] deps = this.dependentBeansBF.getDependentBeans("c"); String[] deps = this.dependentBeansFactory.getDependentBeans("c");
assertTrue(Arrays.equals(new String[] { "int", "long" }, deps)); assertTrue(Arrays.equals(new String[] { "int", "long" }, deps));
} }
@Test @Test
public void testIntDependencies() { public void testIntDependencies() {
String[] deps = this.dependentBeansBF.getDependentBeans("int"); String[] deps = this.dependentBeansFactory.getDependentBeans("int");
assertTrue(Arrays.equals(new String[] { "buffer" }, deps)); assertTrue(Arrays.equals(new String[] { "buffer" }, deps));
} }

View File

@@ -200,7 +200,7 @@ public class DefaultListableBeanFactoryTests {
} }
@Test @Test
public void testPrototypeSingletonFactoryBeanIgnoredByNonEagerTypeMatching() { public void testSingletonFactoryBeanIgnoredByNonEagerTypeMatching() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
Properties p = new Properties(); Properties p = new Properties();
p.setProperty("x1.(class)", DummyFactory.class.getName()); p.setProperty("x1.(class)", DummyFactory.class.getName());
@@ -1381,7 +1381,7 @@ public class DefaultListableBeanFactoryTests {
} }
} }
@Test(expected=NoSuchBeanDefinitionException.class) @Test(expected = NoSuchBeanDefinitionException.class)
public void testGetBeanByTypeWithNoneFound() { public void testGetBeanByTypeWithNoneFound() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
lbf.getBean(TestBean.class); lbf.getBean(TestBean.class);
@@ -1397,7 +1397,7 @@ public class DefaultListableBeanFactoryTests {
assertThat(bean.getBeanName(), equalTo("bd1")); assertThat(bean.getBeanName(), equalTo("bd1"));
} }
@Test(expected=NoUniqueBeanDefinitionException.class) @Test(expected = NoUniqueBeanDefinitionException.class)
public void testGetBeanByTypeWithAmbiguity() { public void testGetBeanByTypeWithAmbiguity() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class); RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class);
@@ -1660,7 +1660,7 @@ public class DefaultListableBeanFactoryTests {
* Java method names. In other words, you can't name a method * Java method names. In other words, you can't name a method
* {@code set&amp;FactoryBean(...)}. * {@code set&amp;FactoryBean(...)}.
*/ */
@Test(expected=TypeMismatchException.class) @Test(expected = TypeMismatchException.class)
public void testAutowireBeanWithFactoryBeanByName() { public void testAutowireBeanWithFactoryBeanByName() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(LazyInitFactory.class); RootBeanDefinition bd = new RootBeanDefinition(LazyInitFactory.class);
@@ -2537,7 +2537,7 @@ public class DefaultListableBeanFactoryTests {
assertEquals(expectedNameFromArgs, tb2.getName()); assertEquals(expectedNameFromArgs, tb2.getName());
} }
@Test(expected=IllegalStateException.class) @Test(expected = IllegalStateException.class)
public void testScopingBeanToUnregisteredScopeResultsInAnException() throws Exception { public void testScopingBeanToUnregisteredScopeResultsInAnException() throws Exception {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class); BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -770,7 +770,7 @@ public class BeanFactoryGenericsTests {
} }
@Test @Test
public void testSpr11250() { public void testGenericMatchingWithBeanNameDifferentiation() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setAutowireCandidateResolver(new GenericTypeAwareAutowireCandidateResolver()); bf.setAutowireCandidateResolver(new GenericTypeAwareAutowireCandidateResolver());
@@ -780,8 +780,23 @@ public class BeanFactoryGenericsTests {
new RootBeanDefinition(NumberBean.class, RootBeanDefinition.AUTOWIRE_CONSTRUCTOR, false)); new RootBeanDefinition(NumberBean.class, RootBeanDefinition.AUTOWIRE_CONSTRUCTOR, false));
NumberBean nb = bf.getBean(NumberBean.class); NumberBean nb = bf.getBean(NumberBean.class);
assertNotNull(nb.getDoubleStore()); assertSame(bf.getBean("doubleStore"), nb.getDoubleStore());
assertNotNull(nb.getFloatStore()); assertSame(bf.getBean("floatStore"), nb.getFloatStore());
}
@Test
public void testGenericMatchingWithFullTypeDifferentiation() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setAutowireCandidateResolver(new GenericTypeAwareAutowireCandidateResolver());
bf.registerBeanDefinition("store1", new RootBeanDefinition(DoubleStore.class));
bf.registerBeanDefinition("store2", new RootBeanDefinition(FloatStore.class));
bf.registerBeanDefinition("numberBean",
new RootBeanDefinition(NumberBean.class, RootBeanDefinition.AUTOWIRE_CONSTRUCTOR, false));
NumberBean nb = bf.getBean(NumberBean.class);
assertSame(bf.getBean("store1"), nb.getDoubleStore());
assertSame(bf.getBean("store2"), nb.getFloatStore());
} }
@@ -851,6 +866,14 @@ public class BeanFactoryGenericsTests {
} }
public static class DoubleStore extends NumberStore<Double> {
}
public static class FloatStore extends NumberStore<Float> {
}
public static class NumberBean { public static class NumberBean {
private final NumberStore<Double> doubleStore; private final NumberStore<Double> doubleStore;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -474,7 +474,7 @@ class ConfigurationClassParser {
} }
else { else {
// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar -> // Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
// process it as a @Configuration class // process it as an @Configuration class
this.importStack.registerImport( this.importStack.registerImport(
currentSourceClass.getMetadata(), candidate.getMetadata().getClassName()); currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
processConfigurationClass(candidate.asConfigClass(configClass)); processConfigurationClass(candidate.asConfigClass(configClass));

View File

@@ -156,7 +156,7 @@ public final class ResolvableType implements Serializable {
} }
/** /**
* Return the underlying Java {@link Class} being managed, if available; * Return the underlying Java {@link Class} being managed, if available;
* otherwise {@code null}. * otherwise {@code null}.
*/ */
public Class<?> getRawClass() { public Class<?> getRawClass() {
@@ -1134,8 +1134,9 @@ public final class ResolvableType implements Serializable {
public static ResolvableType forClassWithGenerics(Class<?> sourceClass, ResolvableType... generics) { public static ResolvableType forClassWithGenerics(Class<?> sourceClass, ResolvableType... generics) {
Assert.notNull(sourceClass, "Source class must not be null"); Assert.notNull(sourceClass, "Source class must not be null");
Assert.notNull(generics, "Generics must not be null"); Assert.notNull(generics, "Generics must not be null");
TypeVariable<?>[] typeVariables = sourceClass.getTypeParameters(); TypeVariable<?>[] variables = sourceClass.getTypeParameters();
return forType(sourceClass, new TypeVariablesVariableResolver(typeVariables, generics)); Assert.isTrue(variables.length == generics.length, "Mismatched number of generics specified");
return forType(sourceClass, new TypeVariablesVariableResolver(variables, generics));
} }
/** /**
@@ -1249,20 +1250,19 @@ public final class ResolvableType implements Serializable {
@SuppressWarnings("serial") @SuppressWarnings("serial")
private static class TypeVariablesVariableResolver implements VariableResolver { private static class TypeVariablesVariableResolver implements VariableResolver {
private final TypeVariable<?>[] typeVariables; private final TypeVariable<?>[] variables;
private final ResolvableType[] generics; private final ResolvableType[] generics;
public TypeVariablesVariableResolver(TypeVariable<?>[] typeVariables, ResolvableType[] generics) { public TypeVariablesVariableResolver(TypeVariable<?>[] variables, ResolvableType[] generics) {
Assert.isTrue(typeVariables.length == generics.length, "Mismatched number of generics specified"); this.variables = variables;
this.typeVariables = typeVariables;
this.generics = generics; this.generics = generics;
} }
@Override @Override
public ResolvableType resolveVariable(TypeVariable<?> variable) { public ResolvableType resolveVariable(TypeVariable<?> variable) {
for (int i = 0; i < this.typeVariables.length; i++) { for (int i = 0; i < this.variables.length; i++) {
if (SerializableTypeWrapper.unwrap(this.typeVariables[i]).equals( if (SerializableTypeWrapper.unwrap(this.variables[i]).equals(
SerializableTypeWrapper.unwrap(variable))) { SerializableTypeWrapper.unwrap(variable))) {
return this.generics[i]; return this.generics[i];
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -51,7 +51,7 @@ public abstract class ReflectionUtils {
private static final String CGLIB_RENAMED_METHOD_PREFIX = "CGLIB$"; private static final String CGLIB_RENAMED_METHOD_PREFIX = "CGLIB$";
/** /**
* Cache for {@link Class#getDeclaredMethods()}, allowing for fast resolution. * Cache for {@link Class#getDeclaredMethods()}, allowing for fast iteration.
*/ */
private static final Map<Class<?>, Method[]> declaredMethodsCache = private static final Map<Class<?>, Method[]> declaredMethodsCache =
new ConcurrentReferenceHashMap<Class<?>, Method[]>(256); new ConcurrentReferenceHashMap<Class<?>, Method[]>(256);
@@ -440,8 +440,8 @@ public abstract class ReflectionUtils {
* @see java.lang.reflect.Method#setAccessible * @see java.lang.reflect.Method#setAccessible
*/ */
public static void makeAccessible(Method method) { public static void makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && if ((!Modifier.isPublic(method.getModifiers()) ||
!method.isAccessible()) { !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
method.setAccessible(true); method.setAccessible(true);
} }
} }
@@ -455,8 +455,8 @@ public abstract class ReflectionUtils {
* @see java.lang.reflect.Constructor#setAccessible * @see java.lang.reflect.Constructor#setAccessible
*/ */
public static void makeAccessible(Constructor<?> ctor) { public static void makeAccessible(Constructor<?> ctor) {
if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && if ((!Modifier.isPublic(ctor.getModifiers()) ||
!ctor.isAccessible()) { !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
ctor.setAccessible(true); ctor.setAccessible(true);
} }
} }
@@ -466,11 +466,11 @@ public abstract class ReflectionUtils {
* class and superclasses. * class and superclasses.
* <p>The same named method occurring on subclass and superclass will appear * <p>The same named method occurring on subclass and superclass will appear
* twice, unless excluded by a {@link MethodFilter}. * twice, unless excluded by a {@link MethodFilter}.
* @param clazz class to start looking at * @param clazz the class to introspect
* @param mc the callback to invoke for each method * @param mc the callback to invoke for each method
* @see #doWithMethods(Class, MethodCallback, MethodFilter) * @see #doWithMethods(Class, MethodCallback, MethodFilter)
*/ */
public static void doWithMethods(Class<?> clazz, MethodCallback mc) throws IllegalArgumentException { public static void doWithMethods(Class<?> clazz, MethodCallback mc) {
doWithMethods(clazz, mc, null); doWithMethods(clazz, mc, null);
} }
@@ -479,13 +479,11 @@ public abstract class ReflectionUtils {
* class and superclasses (or given interface and super-interfaces). * class and superclasses (or given interface and super-interfaces).
* <p>The same named method occurring on subclass and superclass will appear * <p>The same named method occurring on subclass and superclass will appear
* twice, unless excluded by the specified {@link MethodFilter}. * twice, unless excluded by the specified {@link MethodFilter}.
* @param clazz class to start looking at * @param clazz the class to introspect
* @param mc the callback to invoke for each method * @param mc the callback to invoke for each method
* @param mf the filter that determines the methods to apply the callback to * @param mf the filter that determines the methods to apply the callback to
*/ */
public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) {
throws IllegalArgumentException {
// Keep backing up the inheritance hierarchy. // Keep backing up the inheritance hierarchy.
Method[] methods = getDeclaredMethods(clazz); Method[] methods = getDeclaredMethods(clazz);
for (Method method : methods) { for (Method method : methods) {
@@ -496,7 +494,7 @@ public abstract class ReflectionUtils {
mc.doWith(method); mc.doWith(method);
} }
catch (IllegalAccessException ex) { catch (IllegalAccessException ex) {
throw new IllegalStateException("Shouldn't be illegal to access method '" + method.getName() + "': " + ex); throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + ex);
} }
} }
if (clazz.getSuperclass() != null) { if (clazz.getSuperclass() != null) {
@@ -510,10 +508,11 @@ public abstract class ReflectionUtils {
} }
/** /**
* Get all declared methods on the leaf class and all superclasses. Leaf * Get all declared methods on the leaf class and all superclasses.
* class methods are included first. * Leaf class methods are included first.
* @param leafClass the class to introspect
*/ */
public static Method[] getAllDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { public static Method[] getAllDeclaredMethods(Class<?> leafClass) {
final List<Method> methods = new ArrayList<Method>(32); final List<Method> methods = new ArrayList<Method>(32);
doWithMethods(leafClass, new MethodCallback() { doWithMethods(leafClass, new MethodCallback() {
@Override @Override
@@ -525,11 +524,12 @@ public abstract class ReflectionUtils {
} }
/** /**
* Get the unique set of declared methods on the leaf class and all superclasses. Leaf * Get the unique set of declared methods on the leaf class and all superclasses.
* class methods are included first and while traversing the superclass hierarchy any methods found * Leaf class methods are included first and while traversing the superclass hierarchy
* with signatures matching a method already included are filtered out. * any methods found with signatures matching a method already included are filtered out.
* @param leafClass the class to introspect
*/ */
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) {
final List<Method> methods = new ArrayList<Method>(32); final List<Method> methods = new ArrayList<Method>(32);
doWithMethods(leafClass, new MethodCallback() { doWithMethods(leafClass, new MethodCallback() {
@Override @Override
@@ -562,7 +562,7 @@ public abstract class ReflectionUtils {
} }
/** /**
* This method retrieves {@link Class#getDeclaredMethods()} from a local cache * This variant retrieves {@link Class#getDeclaredMethods()} from a local cache
* in order to avoid the JVM's SecurityManager check and defensive array copying. * in order to avoid the JVM's SecurityManager check and defensive array copying.
*/ */
private static Method[] getDeclaredMethods(Class<?> clazz) { private static Method[] getDeclaredMethods(Class<?> clazz) {
@@ -580,7 +580,7 @@ public abstract class ReflectionUtils {
* @param clazz the target class to analyze * @param clazz the target class to analyze
* @param fc the callback to invoke for each field * @param fc the callback to invoke for each field
*/ */
public static void doWithFields(Class<?> clazz, FieldCallback fc) throws IllegalArgumentException { public static void doWithFields(Class<?> clazz, FieldCallback fc) {
doWithFields(clazz, fc, null); doWithFields(clazz, fc, null);
} }
@@ -591,15 +591,12 @@ public abstract class ReflectionUtils {
* @param fc the callback to invoke for each field * @param fc the callback to invoke for each field
* @param ff the filter that determines the fields to apply the callback to * @param ff the filter that determines the fields to apply the callback to
*/ */
public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff) public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff) {
throws IllegalArgumentException {
// Keep backing up the inheritance hierarchy. // Keep backing up the inheritance hierarchy.
Class<?> targetClass = clazz; Class<?> targetClass = clazz;
do { do {
Field[] fields = targetClass.getDeclaredFields(); Field[] fields = targetClass.getDeclaredFields();
for (Field field : fields) { for (Field field : fields) {
// Skip static and final fields.
if (ff != null && !ff.matches(field)) { if (ff != null && !ff.matches(field)) {
continue; continue;
} }
@@ -607,7 +604,7 @@ public abstract class ReflectionUtils {
fc.doWith(field); fc.doWith(field);
} }
catch (IllegalAccessException ex) { catch (IllegalAccessException ex) {
throw new IllegalStateException("Shouldn't be illegal to access field '" + field.getName() + "': " + ex); throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex);
} }
} }
targetClass = targetClass.getSuperclass(); targetClass = targetClass.getSuperclass();
@@ -619,9 +616,8 @@ public abstract class ReflectionUtils {
* Given the source object and the destination, which must be the same class * Given the source object and the destination, which must be the same class
* or a subclass, copy all fields, including inherited fields. Designed to * or a subclass, copy all fields, including inherited fields. Designed to
* work on objects with public no-arg constructors. * work on objects with public no-arg constructors.
* @throws IllegalArgumentException if the arguments are incompatible
*/ */
public static void shallowCopyFieldState(final Object src, final Object dest) throws IllegalArgumentException { public static void shallowCopyFieldState(final Object src, final Object dest) {
if (src == null) { if (src == null) {
throw new IllegalArgumentException("Source for field copy cannot be null"); throw new IllegalArgumentException("Source for field copy cannot be null");
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -66,8 +66,8 @@ public class ReflectionUtilsTests {
@Test @Test
public void setField() { public void setField() {
final TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField(); TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField();
final Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class); Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class);
ReflectionUtils.makeAccessible(field); ReflectionUtils.makeAccessible(field);
@@ -79,13 +79,6 @@ public class ReflectionUtilsTests {
assertNull(testBean.getName()); assertNull(testBean.getName());
} }
@Test(expected = IllegalStateException.class)
public void setFieldIllegal() {
final TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField();
final Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class);
ReflectionUtils.setField(field, testBean, "FooBar");
}
@Test @Test
public void invokeMethod() throws Exception { public void invokeMethod() throws Exception {
String rob = "Rob Harrop"; String rob = "Rob Harrop";
@@ -94,65 +87,50 @@ public class ReflectionUtilsTests {
bean.setName(rob); bean.setName(rob);
Method getName = TestObject.class.getMethod("getName", (Class[]) null); Method getName = TestObject.class.getMethod("getName", (Class[]) null);
Method setName = TestObject.class.getMethod("setName", new Class[] { String.class }); Method setName = TestObject.class.getMethod("setName", String.class);
Object name = ReflectionUtils.invokeMethod(getName, bean); Object name = ReflectionUtils.invokeMethod(getName, bean);
assertEquals("Incorrect name returned", rob, name); assertEquals("Incorrect name returned", rob, name);
String juergen = "Juergen Hoeller"; String juergen = "Juergen Hoeller";
ReflectionUtils.invokeMethod(setName, bean, new Object[] { juergen }); ReflectionUtils.invokeMethod(setName, bean, juergen);
assertEquals("Incorrect name set", juergen, bean.getName()); assertEquals("Incorrect name set", juergen, bean.getName());
} }
@Test @Test
public void declaresException() throws Exception { public void declaresException() throws Exception {
Method remoteExMethod = A.class.getDeclaredMethod("foo", new Class[] { Integer.class }); Method remoteExMethod = A.class.getDeclaredMethod("foo", Integer.class);
assertTrue(ReflectionUtils.declaresException(remoteExMethod, RemoteException.class)); assertTrue(ReflectionUtils.declaresException(remoteExMethod, RemoteException.class));
assertTrue(ReflectionUtils.declaresException(remoteExMethod, ConnectException.class)); assertTrue(ReflectionUtils.declaresException(remoteExMethod, ConnectException.class));
assertFalse(ReflectionUtils.declaresException(remoteExMethod, NoSuchMethodException.class)); assertFalse(ReflectionUtils.declaresException(remoteExMethod, NoSuchMethodException.class));
assertFalse(ReflectionUtils.declaresException(remoteExMethod, Exception.class)); assertFalse(ReflectionUtils.declaresException(remoteExMethod, Exception.class));
Method illegalExMethod = B.class.getDeclaredMethod("bar", new Class[] { String.class }); Method illegalExMethod = B.class.getDeclaredMethod("bar", String.class);
assertTrue(ReflectionUtils.declaresException(illegalExMethod, IllegalArgumentException.class)); assertTrue(ReflectionUtils.declaresException(illegalExMethod, IllegalArgumentException.class));
assertTrue(ReflectionUtils.declaresException(illegalExMethod, NumberFormatException.class)); assertTrue(ReflectionUtils.declaresException(illegalExMethod, NumberFormatException.class));
assertFalse(ReflectionUtils.declaresException(illegalExMethod, IllegalStateException.class)); assertFalse(ReflectionUtils.declaresException(illegalExMethod, IllegalStateException.class));
assertFalse(ReflectionUtils.declaresException(illegalExMethod, Exception.class)); assertFalse(ReflectionUtils.declaresException(illegalExMethod, Exception.class));
} }
@Test @Test(expected = IllegalArgumentException.class)
public void copySrcToDestinationOfIncorrectClass() { public void copySrcToDestinationOfIncorrectClass() {
TestObject src = new TestObject(); TestObject src = new TestObject();
String dest = new String(); String dest = new String();
try { ReflectionUtils.shallowCopyFieldState(src, dest);
ReflectionUtils.shallowCopyFieldState(src, dest);
fail();
} catch (IllegalArgumentException ex) {
// Ok
}
} }
@Test @Test(expected = IllegalArgumentException.class)
public void rejectsNullSrc() { public void rejectsNullSrc() {
TestObject src = null; TestObject src = null;
String dest = new String(); String dest = new String();
try { ReflectionUtils.shallowCopyFieldState(src, dest);
ReflectionUtils.shallowCopyFieldState(src, dest);
fail();
} catch (IllegalArgumentException ex) {
// Ok
}
} }
@Test @Test(expected = IllegalArgumentException.class)
public void rejectsNullDest() { public void rejectsNullDest() {
TestObject src = new TestObject(); TestObject src = new TestObject();
String dest = null; String dest = null;
try { ReflectionUtils.shallowCopyFieldState(src, dest);
ReflectionUtils.shallowCopyFieldState(src, dest);
fail();
} catch (IllegalArgumentException ex) {
// Ok
}
} }
@Test @Test

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -43,8 +43,7 @@ import org.springframework.util.Assert;
* @since 4.0 * @since 4.0
* @see HttpAsyncClient * @see HttpAsyncClient
*/ */
public class HttpComponentsAsyncClientHttpRequestFactory public class HttpComponentsAsyncClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory
extends HttpComponentsClientHttpRequestFactory
implements AsyncClientHttpRequestFactory, InitializingBean { implements AsyncClientHttpRequestFactory, InitializingBean {
private CloseableHttpAsyncClient httpAsyncClient; private CloseableHttpAsyncClient httpAsyncClient;
@@ -86,7 +85,7 @@ public class HttpComponentsAsyncClientHttpRequestFactory
/** /**
* Set the {@code HttpClient} used for * Set the {@code HttpClient} used for
* {@linkplain #createAsyncRequest(java.net.URI, org.springframework.http.HttpMethod) asynchronous execution}. * {@linkplain #createAsyncRequest(URI, HttpMethod) asynchronous execution}.
*/ */
public void setHttpAsyncClient(CloseableHttpAsyncClient httpAsyncClient) { public void setHttpAsyncClient(CloseableHttpAsyncClient httpAsyncClient) {
this.httpAsyncClient = httpAsyncClient; this.httpAsyncClient = httpAsyncClient;
@@ -97,9 +96,10 @@ public class HttpComponentsAsyncClientHttpRequestFactory
* {@linkplain #createAsyncRequest(URI, HttpMethod) asynchronous execution}. * {@linkplain #createAsyncRequest(URI, HttpMethod) asynchronous execution}.
*/ */
public CloseableHttpAsyncClient getHttpAsyncClient() { public CloseableHttpAsyncClient getHttpAsyncClient() {
return httpAsyncClient; return this.httpAsyncClient;
} }
@Override @Override
public void afterPropertiesSet() { public void afterPropertiesSet() {
startAsyncClient(); startAsyncClient();

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -19,7 +19,7 @@ package org.springframework.http.converter;
import org.springframework.core.NestedRuntimeException; import org.springframework.core.NestedRuntimeException;
/** /**
* Thrown by {@link HttpMessageConverter} implementations when the conversion fails. * Thrown by {@link HttpMessageConverter} implementations when a conversion attempt fails.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0 * @since 3.0
@@ -29,7 +29,6 @@ public class HttpMessageConversionException extends NestedRuntimeException {
/** /**
* Create a new HttpMessageConversionException. * Create a new HttpMessageConversionException.
*
* @param msg the detail message * @param msg the detail message
*/ */
public HttpMessageConversionException(String msg) { public HttpMessageConversionException(String msg) {
@@ -38,7 +37,6 @@ public class HttpMessageConversionException extends NestedRuntimeException {
/** /**
* Create a new HttpMessageConversionException. * Create a new HttpMessageConversionException.
*
* @param msg the detail message * @param msg the detail message
* @param cause the root cause (if any) * @param cause the root cause (if any)
*/ */

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,7 +18,7 @@ package org.springframework.http.converter;
/** /**
* Thrown by {@link HttpMessageConverter} implementations when the * Thrown by {@link HttpMessageConverter} implementations when the
* {@link HttpMessageConverter#read(Class, org.springframework.http.HttpInputMessage) read} method fails. * {@link HttpMessageConverter#read} method fails.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0 * @since 3.0
@@ -28,7 +28,6 @@ public class HttpMessageNotReadableException extends HttpMessageConversionExcept
/** /**
* Create a new HttpMessageNotReadableException. * Create a new HttpMessageNotReadableException.
*
* @param msg the detail message * @param msg the detail message
*/ */
public HttpMessageNotReadableException(String msg) { public HttpMessageNotReadableException(String msg) {
@@ -37,11 +36,11 @@ public class HttpMessageNotReadableException extends HttpMessageConversionExcept
/** /**
* Create a new HttpMessageNotReadableException. * Create a new HttpMessageNotReadableException.
*
* @param msg the detail message * @param msg the detail message
* @param cause the root cause (if any) * @param cause the root cause (if any)
*/ */
public HttpMessageNotReadableException(String msg, Throwable cause) { public HttpMessageNotReadableException(String msg, Throwable cause) {
super(msg, cause); super(msg, cause);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,9 +17,8 @@
package org.springframework.http.converter; package org.springframework.http.converter;
/** /**
* Thrown by {@link org.springframework.http.converter.HttpMessageConverter} implementations when the * Thrown by {@link HttpMessageConverter} implementations when the
* {@link org.springframework.http.converter.HttpMessageConverter#write(Object, org.springframework.http.MediaType, * {@link HttpMessageConverter#write} method fails.
* org.springframework.http.HttpOutputMessage) write} method fails.
* *
* @author Arjen Poutsma * @author Arjen Poutsma
* @since 3.0 * @since 3.0
@@ -29,7 +28,6 @@ public class HttpMessageNotWritableException extends HttpMessageConversionExcept
/** /**
* Create a new HttpMessageNotWritableException. * Create a new HttpMessageNotWritableException.
*
* @param msg the detail message * @param msg the detail message
*/ */
public HttpMessageNotWritableException(String msg) { public HttpMessageNotWritableException(String msg) {
@@ -38,11 +36,11 @@ public class HttpMessageNotWritableException extends HttpMessageConversionExcept
/** /**
* Create a new HttpMessageNotWritableException. * Create a new HttpMessageNotWritableException.
*
* @param msg the detail message * @param msg the detail message
* @param cause the root cause (if any) * @param cause the root cause (if any)
*/ */
public HttpMessageNotWritableException(String msg, Throwable cause) { public HttpMessageNotWritableException(String msg, Throwable cause) {
super(msg, cause); super(msg, cause);
} }
} }