Rename modules {org.springframework.*=>spring-*}

This renaming more intuitively expresses the relationship between
subprojects and the JAR artifacts they produce.

Tracking history across these renames is possible, but it requires
use of the --follow flag to `git log`, for example

    $ git log spring-aop/src/main/java/org/springframework/aop/Advisor.java

will show history up until the renaming event, where

    $ git log --follow spring-aop/src/main/java/org/springframework/aop/Advisor.java

will show history for all changes to the file, before and after the
renaming.

See http://chrisbeams.com/git-diff-across-renamed-directories
This commit is contained in:
Chris Beams
2012-01-20 22:51:02 +01:00
parent b6cb514d38
commit 02a4473c62
5671 changed files with 20 additions and 32 deletions

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2002-2008 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.beans;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
/**
* @author Rod Johnson
* @author Chris Beams
*/
public abstract class AbstractPropertyValuesTests {
/**
* Must contain: forname=Tony surname=Blair age=50
*/
protected void doTestTony(PropertyValues pvs) throws Exception {
assertTrue("Contains 3", pvs.getPropertyValues().length == 3);
assertTrue("Contains forname", pvs.contains("forname"));
assertTrue("Contains surname", pvs.contains("surname"));
assertTrue("Contains age", pvs.contains("age"));
assertTrue("Doesn't contain tory", !pvs.contains("tory"));
PropertyValue[] ps = pvs.getPropertyValues();
Map<String, String> m = new HashMap<String, String>();
m.put("forname", "Tony");
m.put("surname", "Blair");
m.put("age", "50");
for (int i = 0; i < ps.length; i++) {
Object val = m.get(ps[i].getName());
assertTrue("Can't have unexpected value", val != null);
assertTrue("Val i string", val instanceof String);
assertTrue("val matches expected", val.equals(ps[i].getValue()));
m.remove(ps[i].getName());
}
assertTrue("Map size is 0", m.size() == 0);
}
}

View File

@@ -0,0 +1,380 @@
/*
* Copyright 2002-2008 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.beans;
import static org.junit.Assert.*;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceEditor;
import test.beans.DerivedTestBean;
import test.beans.ITestBean;
import test.beans.TestBean;
/**
* Unit tests for {@link BeanUtils}.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Chris Beams
* @since 19.05.2003
*/
public final class BeanUtilsTests {
@Test
public void testInstantiateClass() {
// give proper class
BeanUtils.instantiateClass(ArrayList.class);
try {
// give interface
BeanUtils.instantiateClass(List.class);
fail("Should have thrown FatalBeanException");
}
catch (FatalBeanException ex) {
// expected
}
try {
// give class without default constructor
BeanUtils.instantiateClass(CustomDateEditor.class);
fail("Should have thrown FatalBeanException");
}
catch (FatalBeanException ex) {
// expected
}
}
@Test
public void testGetPropertyDescriptors() throws Exception {
PropertyDescriptor[] actual = Introspector.getBeanInfo(TestBean.class).getPropertyDescriptors();
PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(TestBean.class);
assertNotNull("Descriptors should not be null", descriptors);
assertEquals("Invalid number of descriptors returned", actual.length, descriptors.length);
}
@Test
public void testBeanPropertyIsArray() {
PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(ContainerBean.class);
for (int i = 0; i < descriptors.length; i++) {
PropertyDescriptor descriptor = descriptors[i];
if ("containedBeans".equals(descriptor.getName())) {
assertTrue("Property should be an array", descriptor.getPropertyType().isArray());
assertEquals(descriptor.getPropertyType().getComponentType(), ContainedBean.class);
}
}
}
@Test
public void testFindEditorByConvention() {
assertEquals(ResourceEditor.class, BeanUtils.findEditorByConvention(Resource.class).getClass());
}
@Test
public void testCopyProperties() throws Exception {
TestBean tb = new TestBean();
tb.setName("rod");
tb.setAge(32);
tb.setTouchy("touchy");
TestBean tb2 = new TestBean();
assertTrue("Name empty", tb2.getName() == null);
assertTrue("Age empty", tb2.getAge() == 0);
assertTrue("Touchy empty", tb2.getTouchy() == null);
BeanUtils.copyProperties(tb, tb2);
assertTrue("Name copied", tb2.getName().equals(tb.getName()));
assertTrue("Age copied", tb2.getAge() == tb.getAge());
assertTrue("Touchy copied", tb2.getTouchy().equals(tb.getTouchy()));
}
@Test
public void testCopyPropertiesWithDifferentTypes1() throws Exception {
DerivedTestBean tb = new DerivedTestBean();
tb.setName("rod");
tb.setAge(32);
tb.setTouchy("touchy");
TestBean tb2 = new TestBean();
assertTrue("Name empty", tb2.getName() == null);
assertTrue("Age empty", tb2.getAge() == 0);
assertTrue("Touchy empty", tb2.getTouchy() == null);
BeanUtils.copyProperties(tb, tb2);
assertTrue("Name copied", tb2.getName().equals(tb.getName()));
assertTrue("Age copied", tb2.getAge() == tb.getAge());
assertTrue("Touchy copied", tb2.getTouchy().equals(tb.getTouchy()));
}
@Test
public void testCopyPropertiesWithDifferentTypes2() throws Exception {
TestBean tb = new TestBean();
tb.setName("rod");
tb.setAge(32);
tb.setTouchy("touchy");
DerivedTestBean tb2 = new DerivedTestBean();
assertTrue("Name empty", tb2.getName() == null);
assertTrue("Age empty", tb2.getAge() == 0);
assertTrue("Touchy empty", tb2.getTouchy() == null);
BeanUtils.copyProperties(tb, tb2);
assertTrue("Name copied", tb2.getName().equals(tb.getName()));
assertTrue("Age copied", tb2.getAge() == tb.getAge());
assertTrue("Touchy copied", tb2.getTouchy().equals(tb.getTouchy()));
}
@Test
public void testCopyPropertiesWithEditable() throws Exception {
TestBean tb = new TestBean();
assertTrue("Name empty", tb.getName() == null);
tb.setAge(32);
tb.setTouchy("bla");
TestBean tb2 = new TestBean();
tb2.setName("rod");
assertTrue("Age empty", tb2.getAge() == 0);
assertTrue("Touchy empty", tb2.getTouchy() == null);
// "touchy" should not be copied: it's not defined in ITestBean
BeanUtils.copyProperties(tb, tb2, ITestBean.class);
assertTrue("Name copied", tb2.getName() == null);
assertTrue("Age copied", tb2.getAge() == 32);
assertTrue("Touchy still empty", tb2.getTouchy() == null);
}
@Test
public void testCopyPropertiesWithIgnore() throws Exception {
TestBean tb = new TestBean();
assertTrue("Name empty", tb.getName() == null);
tb.setAge(32);
tb.setTouchy("bla");
TestBean tb2 = new TestBean();
tb2.setName("rod");
assertTrue("Age empty", tb2.getAge() == 0);
assertTrue("Touchy empty", tb2.getTouchy() == null);
// "spouse", "touchy", "age" should not be copied
BeanUtils.copyProperties(tb, tb2, new String[]{"spouse", "touchy", "age"});
assertTrue("Name copied", tb2.getName() == null);
assertTrue("Age still empty", tb2.getAge() == 0);
assertTrue("Touchy still empty", tb2.getTouchy() == null);
}
@Test
public void testCopyPropertiesWithIgnoredNonExistingProperty() {
NameAndSpecialProperty source = new NameAndSpecialProperty();
source.setName("name");
TestBean target = new TestBean();
BeanUtils.copyProperties(source, target, new String[]{"specialProperty"});
assertEquals(target.getName(), "name");
}
@Test
public void testResolveSimpleSignature() throws Exception {
Method desiredMethod = MethodSignatureBean.class.getMethod("doSomething");
assertSignatureEquals(desiredMethod, "doSomething");
assertSignatureEquals(desiredMethod, "doSomething()");
}
@Test
public void testResolveInvalidSignature() throws Exception {
try {
BeanUtils.resolveSignature("doSomething(", MethodSignatureBean.class);
fail("Should not be able to parse with opening but no closing paren.");
}
catch (IllegalArgumentException ex) {
// success
}
try {
BeanUtils.resolveSignature("doSomething)", MethodSignatureBean.class);
fail("Should not be able to parse with closing but no opening paren.");
}
catch (IllegalArgumentException ex) {
// success
}
}
@Test
public void testResolveWithAndWithoutArgList() throws Exception {
Method desiredMethod = MethodSignatureBean.class.getMethod("doSomethingElse", new Class[]{String.class, int.class});
assertSignatureEquals(desiredMethod, "doSomethingElse");
assertNull(BeanUtils.resolveSignature("doSomethingElse()", MethodSignatureBean.class));
}
@Test
public void testResolveTypedSignature() throws Exception {
Method desiredMethod = MethodSignatureBean.class.getMethod("doSomethingElse", new Class[]{String.class, int.class});
assertSignatureEquals(desiredMethod, "doSomethingElse(java.lang.String, int)");
}
@Test
public void testResolveOverloadedSignature() throws Exception {
// test resolve with no args
Method desiredMethod = MethodSignatureBean.class.getMethod("overloaded");
assertSignatureEquals(desiredMethod, "overloaded()");
// resolve with single arg
desiredMethod = MethodSignatureBean.class.getMethod("overloaded", new Class[]{String.class});
assertSignatureEquals(desiredMethod, "overloaded(java.lang.String)");
// resolve with two args
desiredMethod = MethodSignatureBean.class.getMethod("overloaded", new Class[]{String.class, BeanFactory.class});
assertSignatureEquals(desiredMethod, "overloaded(java.lang.String, org.springframework.beans.factory.BeanFactory)");
}
@Test
public void testResolveSignatureWithArray() throws Exception {
Method desiredMethod = MethodSignatureBean.class.getMethod("doSomethingWithAnArray", new Class[]{String[].class});
assertSignatureEquals(desiredMethod, "doSomethingWithAnArray(java.lang.String[])");
desiredMethod = MethodSignatureBean.class.getMethod("doSomethingWithAMultiDimensionalArray", new Class[]{String[][].class});
assertSignatureEquals(desiredMethod, "doSomethingWithAMultiDimensionalArray(java.lang.String[][])");
}
@Test
public void testSPR6063() {
PropertyDescriptor[] descrs = BeanUtils.getPropertyDescriptors(Bean.class);
PropertyDescriptor keyDescr = BeanUtils.getPropertyDescriptor(Bean.class, "value");
assertEquals(String.class, keyDescr.getPropertyType());
for (PropertyDescriptor propertyDescriptor : descrs) {
if (propertyDescriptor.getName().equals(keyDescr.getName())) {
assertEquals(propertyDescriptor.getName() + " has unexpected type", keyDescr.getPropertyType(), propertyDescriptor.getPropertyType());
}
}
}
private void assertSignatureEquals(Method desiredMethod, String signature) {
assertEquals(desiredMethod, BeanUtils.resolveSignature(signature, MethodSignatureBean.class));
}
private static class NameAndSpecialProperty {
private String name;
private int specialProperty;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setSpecialProperty(int specialProperty) {
this.specialProperty = specialProperty;
}
public int getSpecialProperty() {
return specialProperty;
}
}
private static class ContainerBean {
private ContainedBean[] containedBeans;
public ContainedBean[] getContainedBeans() {
return containedBeans;
}
public void setContainedBeans(ContainedBean[] containedBeans) {
this.containedBeans = containedBeans;
}
}
private static class ContainedBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
private static class MethodSignatureBean {
public void doSomething() {
}
public void doSomethingElse(String s, int x) {
}
public void overloaded() {
}
public void overloaded(String s) {
}
public void overloaded(String s, BeanFactory beanFactory) {
}
public void doSomethingWithAnArray(String[] strings) {
}
public void doSomethingWithAMultiDimensionalArray(String[][] strings) {
}
}
private interface MapEntry<K, V> {
K getKey();
void setKey(V value);
V getValue();
void setValue(V value);
}
private static class Bean implements MapEntry<String, String> {
private String key;
private String value;
public String getKey() {
return key;
}
public void setKey(String aKey) {
key = aKey;
}
public String getValue() {
return value;
}
public void setValue(String aValue) {
value = aValue;
}
}
}

View File

@@ -0,0 +1,259 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Keith Donald
* @author Juergen Hoeller
*/
public class BeanWrapperAutoGrowingTests {
Bean bean = new Bean();
BeanWrapperImpl wrapper = new BeanWrapperImpl(bean);
@Before
public void setUp() {
wrapper.setAutoGrowNestedPaths(true);
}
@Test
public void getPropertyValueNullValueInNestedPath() {
assertNull(wrapper.getPropertyValue("nested.prop"));
}
@Test
public void setPropertyValueNullValueInNestedPath() {
wrapper.setPropertyValue("nested.prop", "test");
assertEquals("test", bean.getNested().getProp());
}
@Test(expected=NullValueInNestedPathException.class)
public void getPropertyValueNullValueInNestedPathNoDefaultConstructor() {
wrapper.getPropertyValue("nestedNoConstructor.prop");
}
@Test
public void getPropertyValueAutoGrowArray() {
assertNotNull(wrapper.getPropertyValue("array[0]"));
assertEquals(1, bean.getArray().length);
assertTrue(bean.getArray()[0] instanceof Bean);
}
@Test
public void setPropertyValueAutoGrowArray() {
wrapper.setPropertyValue("array[0].prop", "test");
assertEquals("test", bean.getArray()[0].getProp());
}
@Test
public void getPropertyValueAutoGrowArrayBySeveralElements() {
assertNotNull(wrapper.getPropertyValue("array[4]"));
assertEquals(5, bean.getArray().length);
assertTrue(bean.getArray()[0] instanceof Bean);
assertTrue(bean.getArray()[1] instanceof Bean);
assertTrue(bean.getArray()[2] instanceof Bean);
assertTrue(bean.getArray()[3] instanceof Bean);
assertTrue(bean.getArray()[4] instanceof Bean);
assertNotNull(wrapper.getPropertyValue("array[0]"));
assertNotNull(wrapper.getPropertyValue("array[1]"));
assertNotNull(wrapper.getPropertyValue("array[2]"));
assertNotNull(wrapper.getPropertyValue("array[3]"));
}
@Test
public void getPropertyValueAutoGrowMultiDimensionalArray() {
assertNotNull(wrapper.getPropertyValue("multiArray[0][0]"));
assertEquals(1, bean.getMultiArray()[0].length);
assertTrue(bean.getMultiArray()[0][0] instanceof Bean);
}
@Test
public void getPropertyValueAutoGrowList() {
assertNotNull(wrapper.getPropertyValue("list[0]"));
assertEquals(1, bean.getList().size());
assertTrue(bean.getList().get(0) instanceof Bean);
}
@Test
public void setPropertyValueAutoGrowList() {
wrapper.setPropertyValue("list[0].prop", "test");
assertEquals("test", bean.getList().get(0).getProp());
}
@Test
public void getPropertyValueAutoGrowListBySeveralElements() {
assertNotNull(wrapper.getPropertyValue("list[4]"));
assertEquals(5, bean.getList().size());
assertTrue(bean.getList().get(0) instanceof Bean);
assertTrue(bean.getList().get(1) instanceof Bean);
assertTrue(bean.getList().get(2) instanceof Bean);
assertTrue(bean.getList().get(3) instanceof Bean);
assertTrue(bean.getList().get(4) instanceof Bean);
assertNotNull(wrapper.getPropertyValue("list[0]"));
assertNotNull(wrapper.getPropertyValue("list[1]"));
assertNotNull(wrapper.getPropertyValue("list[2]"));
assertNotNull(wrapper.getPropertyValue("list[3]"));
}
@Test
public void getPropertyValueAutoGrowListFailsAgainstLimit() {
wrapper.setAutoGrowCollectionLimit(2);
try {
assertNotNull(wrapper.getPropertyValue("list[4]"));
fail("Should have thrown InvalidPropertyException");
}
catch (InvalidPropertyException ex) {
// expected
assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException);
}
}
@Test
public void getPropertyValueAutoGrowMultiDimensionalList() {
assertNotNull(wrapper.getPropertyValue("multiList[0][0]"));
assertEquals(1, bean.getMultiList().get(0).size());
assertTrue(bean.getMultiList().get(0).get(0) instanceof Bean);
}
@Test(expected=InvalidPropertyException.class)
public void getPropertyValueAutoGrowListNotParameterized() {
wrapper.getPropertyValue("listNotParameterized[0]");
}
@Test
public void setPropertyValueAutoGrowMap() {
wrapper.setPropertyValue("map[A]", new Bean());
assertTrue(bean.getMap().get("A") instanceof Bean);
}
@Test
public void setNestedPropertyValueAutoGrowMap() {
wrapper.setPropertyValue("map[A].nested", new Bean());
assertTrue(bean.getMap().get("A").getNested() instanceof Bean);
}
public static class Bean {
private String prop;
private Bean nested;
private NestedNoDefaultConstructor nestedNoConstructor;
private Bean[] array;
private Bean[][] multiArray;
private List<Bean> list;
private List<List<Bean>> multiList;
private List listNotParameterized;
private Map<String, Bean> map;
public String getProp() {
return prop;
}
public void setProp(String prop) {
this.prop = prop;
}
public Bean getNested() {
return nested;
}
public void setNested(Bean nested) {
this.nested = nested;
}
public Bean[] getArray() {
return array;
}
public void setArray(Bean[] array) {
this.array = array;
}
public Bean[][] getMultiArray() {
return multiArray;
}
public void setMultiArray(Bean[][] multiArray) {
this.multiArray = multiArray;
}
public List<Bean> getList() {
return list;
}
public void setList(List<Bean> list) {
this.list = list;
}
public List<List<Bean>> getMultiList() {
return multiList;
}
public void setMultiList(List<List<Bean>> multiList) {
this.multiList = multiList;
}
public NestedNoDefaultConstructor getNestedNoConstructor() {
return nestedNoConstructor;
}
public void setNestedNoConstructor(NestedNoDefaultConstructor nestedNoConstructor) {
this.nestedNoConstructor = nestedNoConstructor;
}
public List getListNotParameterized() {
return listNotParameterized;
}
public void setListNotParameterized(List listNotParameterized) {
this.listNotParameterized = listNotParameterized;
}
public Map<String, Bean> getMap() {
return map;
}
public void setMap(Map<String, Bean> map) {
this.map = map;
}
}
public static class NestedNoDefaultConstructor {
private NestedNoDefaultConstructor() {
}
}
}

View File

@@ -0,0 +1,112 @@
/*
* 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.beans;
import static org.junit.Assert.*;
import org.junit.Test;
import test.beans.CustomEnum;
import test.beans.GenericBean;
/**
* @author Juergen Hoeller
* @author Chris Beams
*/
public final class BeanWrapperEnumTests {
@Test
public void testCustomEnum() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnum", "VALUE_1");
assertEquals(CustomEnum.VALUE_1, gb.getCustomEnum());
}
@Test
public void testCustomEnumWithNull() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnum", null);
assertEquals(null, gb.getCustomEnum());
}
@Test
public void testCustomEnumWithEmptyString() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnum", "");
assertEquals(null, gb.getCustomEnum());
}
@Test
public void testCustomEnumArrayWithSingleValue() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumArray", "VALUE_1");
assertEquals(1, gb.getCustomEnumArray().length);
assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]);
}
@Test
public void testCustomEnumArrayWithMultipleValues() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumArray", new String[] {"VALUE_1", "VALUE_2"});
assertEquals(2, gb.getCustomEnumArray().length);
assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]);
assertEquals(CustomEnum.VALUE_2, gb.getCustomEnumArray()[1]);
}
@Test
public void testCustomEnumArrayWithMultipleValuesAsCsv() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumArray", "VALUE_1,VALUE_2");
assertEquals(2, gb.getCustomEnumArray().length);
assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]);
assertEquals(CustomEnum.VALUE_2, gb.getCustomEnumArray()[1]);
}
@Test
public void testCustomEnumSetWithSingleValue() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumSet", "VALUE_1");
assertEquals(1, gb.getCustomEnumSet().size());
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1));
}
@Test
public void testCustomEnumSetWithMultipleValues() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumSet", new String[] {"VALUE_1", "VALUE_2"});
assertEquals(2, gb.getCustomEnumSet().size());
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1));
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2));
}
@Test
public void testCustomEnumSetWithMultipleValuesAsCsv() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumSet", "VALUE_1,VALUE_2");
assertEquals(2, gb.getCustomEnumSet().size());
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1));
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2));
}
}

View File

@@ -0,0 +1,625 @@
/*
* Copyright 2002-2010 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.beans;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.*;
import org.junit.Test;
import test.beans.GenericBean;
import test.beans.GenericIntegerBean;
import test.beans.GenericSetOfIntegerBean;
import test.beans.TestBean;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @since 18.01.2006
*/
public class BeanWrapperGenericsTests {
@Test
public void testGenericSet() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
Set<String> input = new HashSet<String>();
input.add("4");
input.add("5");
bw.setPropertyValue("integerSet", input);
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
}
@Test
public void testGenericLowerBoundedSet() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, true));
Set<String> input = new HashSet<String>();
input.add("4");
input.add("5");
bw.setPropertyValue("numberSet", input);
assertTrue(gb.getNumberSet().contains(new Integer(4)));
assertTrue(gb.getNumberSet().contains(new Integer(5)));
}
@Test
public void testGenericSetWithConversionFailure() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
Set<TestBean> input = new HashSet<TestBean>();
input.add(new TestBean());
try {
bw.setPropertyValue("integerSet", input);
fail("Should have thrown TypeMismatchException");
}
catch (TypeMismatchException ex) {
assertTrue(ex.getMessage().indexOf("java.lang.Integer") != -1);
}
}
@Test
public void testGenericList() throws MalformedURLException {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
List<String> input = new ArrayList<String>();
input.add("http://localhost:8080");
input.add("http://localhost:9090");
bw.setPropertyValue("resourceList", input);
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
@Test
public void testGenericListElement() throws MalformedURLException {
GenericBean<?> gb = new GenericBean<Object>();
gb.setResourceList(new ArrayList<Resource>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("resourceList[0]", "http://localhost:8080");
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
}
@Test
public void testGenericMap() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
Map<String, String> input = new HashMap<String, String>();
input.put("4", "5");
input.put("6", "7");
bw.setPropertyValue("shortMap", input);
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
}
@Test
public void testGenericMapElement() {
GenericBean<?> gb = new GenericBean<Object>();
gb.setShortMap(new HashMap<Short, Integer>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("shortMap[4]", "5");
assertEquals(new Integer(5), bw.getPropertyValue("shortMap[4]"));
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
}
@Test
public void testGenericMapWithKeyType() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
Map<String, String> input = new HashMap<String, String>();
input.put("4", "5");
input.put("6", "7");
bw.setPropertyValue("longMap", input);
assertEquals("5", gb.getLongMap().get(new Long("4")));
assertEquals("7", gb.getLongMap().get(new Long("6")));
}
@Test
public void testGenericMapElementWithKeyType() {
GenericBean<?> gb = new GenericBean<Object>();
gb.setLongMap(new HashMap<Long, Integer>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("longMap[4]", "5");
assertEquals("5", gb.getLongMap().get(new Long("4")));
assertEquals("5", bw.getPropertyValue("longMap[4]"));
}
@Test
public void testGenericMapWithCollectionValue() {
GenericBean<?> gb = new GenericBean<Object>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
@SuppressWarnings("unchecked")
Map<String, Collection> input = new HashMap<String, Collection>();
HashSet<Integer> value1 = new HashSet<Integer>();
value1.add(new Integer(1));
input.put("1", value1);
ArrayList<Boolean> value2 = new ArrayList<Boolean>();
value2.add(Boolean.TRUE);
input.put("2", value2);
bw.setPropertyValue("collectionMap", input);
assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet);
assertTrue(gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList);
}
@Test
public void testGenericMapElementWithCollectionValue() {
GenericBean<?> gb = new GenericBean<Object>();
gb.setCollectionMap(new HashMap<Number, Collection<? extends Object>>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
HashSet<Integer> value1 = new HashSet<Integer>();
value1.add(new Integer(1));
bw.setPropertyValue("collectionMap[1]", value1);
assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet);
}
@Test
public void testGenericListOfLists() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
List<List<Integer>> list = new LinkedList<List<Integer>>();
list.add(new LinkedList<Integer>());
gb.setListOfLists(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfLists[0][0]", new Integer(5));
assertEquals(new Integer(5), bw.getPropertyValue("listOfLists[0][0]"));
assertEquals(new Integer(5), gb.getListOfLists().get(0).get(0));
}
@Test
public void testGenericListOfListsWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
List<List<Integer>> list = new LinkedList<List<Integer>>();
list.add(new LinkedList<Integer>());
gb.setListOfLists(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfLists[0][0]", "5");
assertEquals(new Integer(5), bw.getPropertyValue("listOfLists[0][0]"));
assertEquals(new Integer(5), gb.getListOfLists().get(0).get(0));
}
@Test
public void testGenericListOfArrays() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
ArrayList<String[]> list = new ArrayList<String[]>();
list.add(new String[] {"str1", "str2"});
gb.setListOfArrays(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfArrays[0][1]", "str3 ");
assertEquals("str3 ", bw.getPropertyValue("listOfArrays[0][1]"));
assertEquals("str3 ", gb.getListOfArrays().get(0)[1]);
}
@Test
public void testGenericListOfArraysWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
ArrayList<String[]> list = new ArrayList<String[]>();
list.add(new String[] {"str1", "str2"});
gb.setListOfArrays(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(String.class, new StringTrimmerEditor(false));
bw.setPropertyValue("listOfArrays[0][1]", "str3 ");
assertEquals("str3", bw.getPropertyValue("listOfArrays[0][1]"));
assertEquals("str3", gb.getListOfArrays().get(0)[1]);
}
@Test
public void testGenericListOfMaps() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
List<Map<Integer, Long>> list = new LinkedList<Map<Integer, Long>>();
list.add(new HashMap<Integer, Long>());
gb.setListOfMaps(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMaps[0][10]", new Long(5));
assertEquals(new Long(5), bw.getPropertyValue("listOfMaps[0][10]"));
assertEquals(new Long(5), gb.getListOfMaps().get(0).get(10));
}
@Test
public void testGenericListOfMapsWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
List<Map<Integer, Long>> list = new LinkedList<Map<Integer, Long>>();
list.add(new HashMap<Integer, Long>());
gb.setListOfMaps(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMaps[0][10]", "5");
assertEquals(new Long(5), bw.getPropertyValue("listOfMaps[0][10]"));
assertEquals(new Long(5), gb.getListOfMaps().get(0).get(10));
}
@Test
public void testGenericMapOfMaps() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
Map<String, Map<Integer, Long>> map = new HashMap<String, Map<Integer, Long>>();
map.put("mykey", new HashMap<Integer, Long>());
gb.setMapOfMaps(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfMaps[mykey][10]", new Long(5));
assertEquals(new Long(5), bw.getPropertyValue("mapOfMaps[mykey][10]"));
assertEquals(new Long(5), gb.getMapOfMaps().get("mykey").get(10));
}
@Test
public void testGenericMapOfMapsWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
Map<String, Map<Integer, Long>> map = new HashMap<String, Map<Integer, Long>>();
map.put("mykey", new HashMap<Integer, Long>());
gb.setMapOfMaps(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfMaps[mykey][10]", "5");
assertEquals(new Long(5), bw.getPropertyValue("mapOfMaps[mykey][10]"));
assertEquals(new Long(5), gb.getMapOfMaps().get("mykey").get(10));
}
@Test
public void testGenericMapOfLists() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
map.put(new Integer(1), new LinkedList<Integer>());
gb.setMapOfLists(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfLists[1][0]", new Integer(5));
assertEquals(new Integer(5), bw.getPropertyValue("mapOfLists[1][0]"));
assertEquals(new Integer(5), gb.getMapOfLists().get(new Integer(1)).get(0));
}
@Test
public void testGenericMapOfListsWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<String>();
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
map.put(new Integer(1), new LinkedList<Integer>());
gb.setMapOfLists(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfLists[1][0]", "5");
assertEquals(new Integer(5), bw.getPropertyValue("mapOfLists[1][0]"));
assertEquals(new Integer(5), gb.getMapOfLists().get(new Integer(1)).get(0));
}
@Test
public void testGenericTypeNestingMapOfInteger() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("testKey", "100");
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfInteger", map);
Object obj = gb.getMapOfInteger().get("testKey");
assertTrue(obj instanceof Integer);
}
@Test
public void testGenericTypeNestingMapOfListOfInteger() throws Exception {
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> list = Arrays.asList(new String[] {"1", "2", "3"});
map.put("testKey", list);
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfListOfInteger", map);
Object obj = gb.getMapOfListOfInteger().get("testKey").get(0);
assertTrue(obj instanceof Integer);
assertEquals(1, ((Integer) obj).intValue());
}
@Test
public void testGenericTypeNestingListOfMapOfInteger() throws Exception {
List<Map<String, String>> list = new LinkedList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
map.put("testKey", "5");
list.add(map);
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMapOfInteger", list);
Object obj = gb.getListOfMapOfInteger().get(0).get("testKey");
assertTrue(obj instanceof Integer);
assertEquals(5, ((Integer) obj).intValue());
}
@Test
public void testGenericTypeNestingMapOfListOfListOfInteger() throws Exception {
Map<String, List<List<String>>> map = new HashMap<String, List<List<String>>>();
List<String> list = Arrays.asList(new String[] {"1", "2", "3"});
map.put("testKey", Collections.singletonList(list));
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfListOfListOfInteger", map);
Object obj = gb.getMapOfListOfListOfInteger().get("testKey").get(0).get(0);
assertTrue(obj instanceof Integer);
assertEquals(1, ((Integer) obj).intValue());
}
@Test
public void testComplexGenericMap() {
Map<List<String>, List<String>> inputMap = new HashMap<List<String>, List<String>>();
List<String> inputKey = new LinkedList<String>();
inputKey.add("1");
List<String> inputValue = new LinkedList<String>();
inputValue.add("10");
inputMap.put(inputKey, inputValue);
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericMap", inputMap);
assertEquals(new Integer(1), holder.getGenericMap().keySet().iterator().next().get(0));
assertEquals(new Long(10), holder.getGenericMap().values().iterator().next().get(0));
}
@Test
public void testComplexGenericMapWithCollectionConversion() {
Map<Set<String>, Set<String>> inputMap = new HashMap<Set<String>, Set<String>>();
Set<String> inputKey = new HashSet<String>();
inputKey.add("1");
Set<String> inputValue = new HashSet<String>();
inputValue.add("10");
inputMap.put(inputKey, inputValue);
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericMap", inputMap);
assertEquals(new Integer(1), holder.getGenericMap().keySet().iterator().next().get(0));
assertEquals(new Long(10), holder.getGenericMap().values().iterator().next().get(0));
}
@Test
public void testComplexGenericIndexedMapEntry() {
List<String> inputValue = new LinkedList<String>();
inputValue.add("10");
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getGenericIndexedMap().keySet().iterator().next());
assertEquals(new Long(10), holder.getGenericIndexedMap().values().iterator().next().get(0));
}
@Test
public void testComplexGenericIndexedMapEntryWithCollectionConversion() {
Set<String> inputValue = new HashSet<String>();
inputValue.add("10");
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getGenericIndexedMap().keySet().iterator().next());
assertEquals(new Long(10), holder.getGenericIndexedMap().values().iterator().next().get(0));
}
@Test
public void testComplexDerivedIndexedMapEntry() {
List<String> inputValue = new LinkedList<String>();
inputValue.add("10");
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("derivedIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getDerivedIndexedMap().keySet().iterator().next());
assertEquals(new Long(10), holder.getDerivedIndexedMap().values().iterator().next().get(0));
}
@Test
public void testComplexDerivedIndexedMapEntryWithCollectionConversion() {
Set<String> inputValue = new HashSet<String>();
inputValue.add("10");
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("derivedIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getDerivedIndexedMap().keySet().iterator().next());
assertEquals(new Long(10), holder.getDerivedIndexedMap().values().iterator().next().get(0));
}
@Test
public void testGenericallyTypedIntegerBean() throws Exception {
GenericIntegerBean gb = new GenericIntegerBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("genericProperty", "10");
bw.setPropertyValue("genericListProperty", new String[] {"20", "30"});
assertEquals(new Integer(10), gb.getGenericProperty());
assertEquals(new Integer(20), gb.getGenericListProperty().get(0));
assertEquals(new Integer(30), gb.getGenericListProperty().get(1));
}
@Test
public void testGenericallyTypedSetOfIntegerBean() throws Exception {
GenericSetOfIntegerBean gb = new GenericSetOfIntegerBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("genericProperty", "10");
bw.setPropertyValue("genericListProperty", new String[] {"20", "30"});
assertEquals(new Integer(10), gb.getGenericProperty().iterator().next());
assertEquals(new Integer(20), gb.getGenericListProperty().get(0).iterator().next());
assertEquals(new Integer(30), gb.getGenericListProperty().get(1).iterator().next());
}
@Test
public void testSettingGenericPropertyWithReadOnlyInterface() {
Bar bar = new Bar();
BeanWrapper bw = new BeanWrapperImpl(bar);
bw.setPropertyValue("version", "10");
assertEquals(new Double(10.0), bar.getVersion());
}
@Test
public void testSettingLongPropertyWithGenericInterface() {
Promotion bean = new Promotion();
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.setPropertyValue("id", "10");
assertEquals(new Long(10), bean.getId());
}
private static abstract class BaseGenericCollectionBean {
public abstract Object getMapOfInteger();
public abstract Map<String, List<Integer>> getMapOfListOfInteger();
public abstract void setMapOfListOfInteger(Map<String, List<Integer>> mapOfListOfInteger);
}
private static class NestedGenericCollectionBean extends BaseGenericCollectionBean {
private Map<String, Integer> mapOfInteger;
private Map<String, List<Integer>> mapOfListOfInteger;
private List<Map<String, Integer>> listOfMapOfInteger;
private Map<String, List<List<Integer>>> mapOfListOfListOfInteger;
public Map<String, Integer> getMapOfInteger() {
return mapOfInteger;
}
public void setMapOfInteger(Map<String, Integer> mapOfInteger) {
this.mapOfInteger = mapOfInteger;
}
public Map<String, List<Integer>> getMapOfListOfInteger() {
return mapOfListOfInteger;
}
public void setMapOfListOfInteger(Map<String, List<Integer>> mapOfListOfInteger) {
this.mapOfListOfInteger = mapOfListOfInteger;
}
public List<Map<String, Integer>> getListOfMapOfInteger() {
return listOfMapOfInteger;
}
public void setListOfMapOfInteger(List<Map<String, Integer>> listOfMapOfInteger) {
this.listOfMapOfInteger = listOfMapOfInteger;
}
public Map<String, List<List<Integer>>> getMapOfListOfListOfInteger() {
return mapOfListOfListOfInteger;
}
public void setMapOfListOfListOfInteger(Map<String, List<List<Integer>>> mapOfListOfListOfInteger) {
this.mapOfListOfListOfInteger = mapOfListOfListOfInteger;
}
}
private static class ComplexMapHolder {
private Map<List<Integer>, List<Long>> genericMap;
private Map<Integer, List<Long>> genericIndexedMap = new HashMap<Integer, List<Long>>();
private DerivedMap derivedIndexedMap = new DerivedMap();
public void setGenericMap(Map<List<Integer>, List<Long>> genericMap) {
this.genericMap = genericMap;
}
public Map<List<Integer>, List<Long>> getGenericMap() {
return genericMap;
}
public void setGenericIndexedMap(Map<Integer, List<Long>> genericIndexedMap) {
this.genericIndexedMap = genericIndexedMap;
}
public Map<Integer, List<Long>> getGenericIndexedMap() {
return genericIndexedMap;
}
public void setDerivedIndexedMap(DerivedMap derivedIndexedMap) {
this.derivedIndexedMap = derivedIndexedMap;
}
public DerivedMap getDerivedIndexedMap() {
return derivedIndexedMap;
}
}
@SuppressWarnings("serial")
private static class DerivedMap extends HashMap<Integer, List<Long>> {
}
public interface Foo {
Number getVersion();
}
public class Bar implements Foo {
private double version;
public Double getVersion() {
return this.version;
}
public void setVersion(Double theDouble) {
this.version = theDouble;
}
}
public interface ObjectWithId<T extends Comparable<T>> {
T getId();
void setId(T aId);
}
public class Promotion implements ObjectWithId<Long> {
private Long id;
public Long getId() {
return id;
}
public void setId(Long aId) {
this.id = aId;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2002-2008 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.beans;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.core.OverridingClassLoader;
import test.beans.TestBean;
/**
* @author Juergen Hoeller
* @author Chris Beams
*/
public final class CachedIntrospectionResultsTests {
@Test
public void testAcceptClassLoader() throws Exception {
BeanWrapper bw = new BeanWrapperImpl(TestBean.class);
assertTrue(bw.isWritableProperty("name"));
assertTrue(bw.isWritableProperty("age"));
assertTrue(CachedIntrospectionResults.classCache.containsKey(TestBean.class));
ClassLoader child = new OverridingClassLoader(getClass().getClassLoader());
Class<?> tbClass = child.loadClass("test.beans.TestBean");
assertFalse(CachedIntrospectionResults.classCache.containsKey(tbClass));
CachedIntrospectionResults.acceptClassLoader(child);
bw = new BeanWrapperImpl(tbClass);
assertTrue(bw.isWritableProperty("name"));
assertTrue(bw.isWritableProperty("age"));
assertTrue(CachedIntrospectionResults.classCache.containsKey(tbClass));
CachedIntrospectionResults.clearClassLoader(child);
assertFalse(CachedIntrospectionResults.classCache.containsKey(tbClass));
assertTrue(CachedIntrospectionResults.classCache.containsKey(TestBean.class));
}
}

View File

@@ -0,0 +1,150 @@
/*
* Copyright 2002-2008 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.beans;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
/**
* @author Guillaume Poirier
* @author Juergen Hoeller
* @author Chris Beams
* @since 08.03.2004
*/
public final class ConcurrentBeanWrapperTests {
private final Log logger = LogFactory.getLog(getClass());
private Set<TestRun> set = Collections.synchronizedSet(new HashSet<TestRun>());
private Throwable ex = null;
@Test
public void testSingleThread() {
for (int i = 0; i < 100; i++) {
performSet();
}
}
@Test
public void testConcurrent() {
for (int i = 0; i < 10; i++) {
TestRun run = new TestRun(this);
set.add(run);
Thread t = new Thread(run);
t.setDaemon(true);
t.start();
}
logger.info("Thread creation over, " + set.size() + " still active.");
synchronized (this) {
while (!set.isEmpty() && ex == null) {
try {
wait();
}
catch (InterruptedException e) {
logger.info(e.toString());
}
logger.info(set.size() + " threads still active.");
}
}
if (ex != null) {
fail(ex.getMessage());
}
}
private static void performSet() {
TestBean bean = new TestBean();
Properties p = (Properties) System.getProperties().clone();
assertTrue("The System properties must not be empty", p.size() != 0);
for (Iterator<?> i = p.entrySet().iterator(); i.hasNext();) {
i.next();
if (Math.random() > 0.9) {
i.remove();
}
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
p.store(buffer, null);
}
catch (IOException e) {
// ByteArrayOutputStream does not throw
// any IOException
}
String value = new String(buffer.toByteArray());
BeanWrapperImpl wrapper = new BeanWrapperImpl(bean);
wrapper.setPropertyValue("properties", value);
assertEquals(p, bean.getProperties());
}
private static class TestRun implements Runnable {
private ConcurrentBeanWrapperTests test;
public TestRun(ConcurrentBeanWrapperTests test) {
this.test = test;
}
public void run() {
try {
for (int i = 0; i < 100; i++) {
performSet();
}
}
catch (Throwable e) {
test.ex = e;
}
finally {
synchronized (test) {
test.set.remove(this);
test.notifyAll();
}
}
}
}
private static class TestBean {
private Properties properties;
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import static org.junit.Assert.assertEquals;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.junit.Test;
/**
* Unit tests for {@link DirectFieldAccessor}
*
* @author Jose Luis Martin
* @author Chris Beams
*/
public class DirectFieldAccessorTests {
@Test
public void withShadowedField() throws Exception {
@SuppressWarnings("serial")
JPanel p = new JPanel() {
@SuppressWarnings("unused")
JTextField name = new JTextField();
};
DirectFieldAccessor dfa = new DirectFieldAccessor(p);
assertEquals(JTextField.class, dfa.getPropertyType("name"));
}
}

View File

@@ -0,0 +1,737 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.beans.BeanInfo;
import java.beans.IndexedPropertyDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.ExtendedBeanInfo.PropertyDescriptorComparator;
import test.beans.TestBean;
/**
* Unit tests for {@link ExtendedBeanInfo}.
*
* @author Chris Beams
* @since 3.1
*/
public class ExtendedBeanInfoTests {
@Test
public void standardReadMethodOnly() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public String getFoo() { return null; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false));
}
@Test
public void standardWriteMethodOnly() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public void setFoo(String f) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
}
@Test
public void standardReadAndWriteMethods() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public void setFoo(String f) { }
public String getFoo() { return null; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
}
@Test
public void nonStandardWriteMethodOnly() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public C setFoo(String foo) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
}
@Test
public void standardReadAndNonStandardWriteMethods() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public String getFoo() { return null; }
public C setFoo(String foo) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
}
@Test
public void standardReadMethodsAndOverloadedNonStandardWriteMethods() throws Exception {
@SuppressWarnings("unused") class C {
public String getFoo() { return null; }
public C setFoo(String foo) { return this; }
public C setFoo(Number foo) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) {
if (pd.getName().equals("foo")) {
assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", String.class)));
return;
}
}
fail("never matched write method");
}
@Test
public void standardReadMethodInSuperclassAndNonStandardWriteMethodInSubclass() throws Exception {
@SuppressWarnings("unused") class B {
public String getFoo() { return null; }
}
@SuppressWarnings("unused") class C extends B {
public C setFoo(String foo) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
}
@Test
public void standardReadMethodInSuperAndSubclassesAndGenericBuilderStyleNonStandardWriteMethodInSuperAndSubclasses() throws Exception {
abstract class B<This extends B<This>> {
@SuppressWarnings("unchecked")
protected final This instance = (This) this;
private String foo;
public String getFoo() { return foo; }
public This setFoo(String foo) {
this.foo = foo;
return this.instance;
}
}
class C extends B<C> {
private int bar = -1;
public int getBar() { return bar; }
public C setBar(int bar) {
this.bar = bar;
return this.instance;
}
}
C c = new C()
.setFoo("blue")
.setBar(42);
assertThat(c.getFoo(), is("blue"));
assertThat(c.getBar(), is(42));
BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
assertThat(hasReadMethodForProperty(bi, "bar"), is(true));
assertThat(hasWriteMethodForProperty(bi, "bar"), is(false));
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));
assertThat(hasReadMethodForProperty(bi, "bar"), is(true));
assertThat(hasWriteMethodForProperty(bi, "bar"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
assertThat(hasReadMethodForProperty(ebi, "bar"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "bar"), is(true));
}
@Test
public void nonPublicStandardReadAndWriteMethods() throws Exception {
@SuppressWarnings("unused") class C {
String getFoo() { return null; }
C setFoo(String foo) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false));
}
/**
* {@link ExtendedBeanInfo} should behave exactly like {@link BeanInfo}
* in strange edge cases.
*/
@Test
public void readMethodReturnsSupertypeOfWriteMethodParameter() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public Number getFoo() { return null; }
public void setFoo(Integer foo) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false));
}
@Test
public void indexedReadMethodReturnsSupertypeOfIndexedWriteMethodParameter() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public Number getFoos(int index) { return null; }
public void setFoos(int index, Integer foo) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true));
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false));
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true));
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false));
}
/**
* {@link ExtendedBeanInfo} should behave exactly like {@link BeanInfo}
* in strange edge cases.
*/
@Test
public void readMethodReturnsSubtypeOfWriteMethodParameter() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public Integer getFoo() { return null; }
public void setFoo(Number foo) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false));
}
@Test
public void indexedReadMethodReturnsSubtypeOfIndexedWriteMethodParameter() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public Integer getFoos(int index) { return null; }
public void setFoo(int index, Number foo) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true));
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false));
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true));
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false));
}
@Test
public void indexedReadMethodOnly() throws IntrospectionException {
@SuppressWarnings("unused")
class C {
// indexed read method
public String getFoos(int i) { return null; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasReadMethodForProperty(bi, "foos"), is(false));
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foos"), is(false));
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true));
}
@Test
public void indexedWriteMethodOnly() throws IntrospectionException {
@SuppressWarnings("unused")
class C {
// indexed write method
public void setFoos(int i, String foo) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasWriteMethodForProperty(bi, "foos"), is(false));
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(false));
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true));
}
@Test
public void indexedReadAndIndexedWriteMethods() throws IntrospectionException {
@SuppressWarnings("unused")
class C {
// indexed read method
public String getFoos(int i) { return null; }
// indexed write method
public void setFoos(int i, String foo) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasReadMethodForProperty(bi, "foos"), is(false));
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foos"), is(false));
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foos"), is(false));
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(false));
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true));
}
@Test
public void readAndWriteAndIndexedReadAndIndexedWriteMethods() throws IntrospectionException {
@SuppressWarnings("unused")
class C {
// read method
public String[] getFoos() { return null; }
// indexed read method
public String getFoos(int i) { return null; }
// write method
public void setFoos(String[] foos) { }
// indexed write method
public void setFoos(int i, String foo) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasReadMethodForProperty(bi, "foos"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foos"), is(true));
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true));
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foos"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true));
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true));
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true));
}
@Test
public void indexedReadAndNonStandardIndexedWrite() throws IntrospectionException {
@SuppressWarnings("unused")
class C {
// indexed read method
public String getFoos(int i) { return null; }
// non-standard indexed write method
public C setFoos(int i, String foo) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true));
// interesting! standard Inspector picks up non-void return types on indexed write methods by default
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true));
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true));
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true));
}
@Test
public void indexedReadAndNonStandardWriteAndNonStandardIndexedWrite() throws IntrospectionException {
@SuppressWarnings("unused")
class C {
// non-standard write method
public C setFoos(String[] foos) { return this; }
// indexed read method
public String getFoos(int i) { return null; }
// non-standard indexed write method
public C setFoos(int i, String foo) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foos"), is(false));
// again as above, standard Inspector picks up non-void return types on indexed write methods by default
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true));
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foos"), is(true));
// again as above, standard Inspector picks up non-void return types on indexed write methods by default
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true));
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true));
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true));
}
@Test
public void subclassWriteMethodWithCovariantReturnType() throws IntrospectionException {
@SuppressWarnings("unused") class B {
public String getFoo() { return null; }
public Number setFoo(String foo) { return null; }
}
class C extends B {
public String getFoo() { return null; }
public Integer setFoo(String foo) { return null; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length));
}
@Test
public void nonStandardReadMethodAndStandardWriteMethod() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public void getFoo() { }
public void setFoo(String foo) { }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false));
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
}
/**
* Ensures that an empty string is not passed into a PropertyDescriptor constructor. This
* could occur when handling ArrayList.set(int,Object)
*/
@Test
public void emptyPropertiesIgnored() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public Object set(Object o) { return null; }
public Object set(int i, Object o) { return null; }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(ebi.getPropertyDescriptors(), equalTo(bi.getPropertyDescriptors()));
}
/**
* Corners the bug revealed by SPR-8522, in which an (apparently) indexed write method
* without a corresponding indexed read method would fail to be processed correctly by
* ExtendedBeanInfo. The local class C below represents the relevant methods from
* Google's GsonBuilder class. Interestingly, the setDateFormat(int, int) method was
* not actually intended to serve as an indexed write method; it just appears that way.
*/
@Test
public void reproSpr8522() throws IntrospectionException {
@SuppressWarnings("unused") class C {
public Object setDateFormat(String pattern) { return new Object(); }
public Object setDateFormat(int style) { return new Object(); }
public Object setDateFormat(int dateStyle, int timeStyle) { return new Object(); }
}
BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "dateFormat"), is(false));
assertThat(hasWriteMethodForProperty(bi, "dateFormat"), is(false));
assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat"), is(false));
assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat"), is(true));
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "dateFormat"), is(false));
assertThat(hasWriteMethodForProperty(bi, "dateFormat"), is(true));
assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat"), is(false));
assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat"), is(true));
assertThat(hasReadMethodForProperty(ebi, "dateFormat"), is(false));
assertThat(hasWriteMethodForProperty(ebi, "dateFormat"), is(true));
assertThat(hasIndexedReadMethodForProperty(ebi, "dateFormat"), is(false));
assertThat(hasIndexedWriteMethodForProperty(ebi, "dateFormat"), is(true));
}
@Test
public void propertyCountsMatch() throws IntrospectionException {
BeanInfo bi = Introspector.getBeanInfo(TestBean.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length));
}
@Test
public void propertyCountsWithNonStandardWriteMethod() throws IntrospectionException {
class ExtendedTestBean extends TestBean {
@SuppressWarnings("unused")
public ExtendedTestBean setFoo(String s) { return this; }
}
BeanInfo bi = Introspector.getBeanInfo(ExtendedTestBean.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
boolean found = false;
for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) {
if (pd.getName().equals("foo")) {
found = true;
}
}
assertThat(found, is(true));
assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length+1));
}
/**
* {@link BeanInfo#getPropertyDescriptors()} returns alphanumerically sorted.
* Test that {@link ExtendedBeanInfo#getPropertyDescriptors()} does the same.
*/
@Test
public void propertyDescriptorOrderIsEqual() throws IntrospectionException {
BeanInfo bi = Introspector.getBeanInfo(TestBean.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
for (int i = 0; i < bi.getPropertyDescriptors().length; i++) {
assertThat("element " + i + " in BeanInfo and ExtendedBeanInfo propertyDescriptor arrays do not match",
ebi.getPropertyDescriptors()[i].getName(), equalTo(bi.getPropertyDescriptors()[i].getName()));
}
}
@Test
public void propertyDescriptorComparator() throws IntrospectionException {
PropertyDescriptorComparator c = new PropertyDescriptorComparator();
assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("a", null, null)), equalTo(0));
assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abc", null, null)), equalTo(0));
assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("b", null, null)), lessThan(0));
assertThat(c.compare(new PropertyDescriptor("b", null, null), new PropertyDescriptor("a", null, null)), greaterThan(0));
assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abd", null, null)), lessThan(0));
assertThat(c.compare(new PropertyDescriptor("xyz", null, null), new PropertyDescriptor("123", null, null)), greaterThan(0));
assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("abc", null, null)), lessThan(0));
assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("a", null, null)), greaterThan(0));
assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("b", null, null)), lessThan(0));
assertThat(c.compare(new PropertyDescriptor(" ", null, null), new PropertyDescriptor("a", null, null)), lessThan(0));
assertThat(c.compare(new PropertyDescriptor("1", null, null), new PropertyDescriptor("a", null, null)), lessThan(0));
assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("A", null, null)), greaterThan(0));
}
private boolean hasWriteMethodForProperty(BeanInfo beanInfo, String propertyName) {
for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
if (pd.getName().equals(propertyName)) {
return pd.getWriteMethod() != null;
}
}
return false;
}
private boolean hasReadMethodForProperty(BeanInfo beanInfo, String propertyName) {
for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
if (pd.getName().equals(propertyName)) {
return pd.getReadMethod() != null;
}
}
return false;
}
private boolean hasIndexedWriteMethodForProperty(BeanInfo beanInfo, String propertyName) {
for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
if (pd.getName().equals(propertyName)) {
assertThat(propertyName + " property is not indexed", pd, instanceOf(IndexedPropertyDescriptor.class));
return ((IndexedPropertyDescriptor)pd).getIndexedWriteMethod() != null;
}
}
return false;
}
private boolean hasIndexedReadMethodForProperty(BeanInfo beanInfo, String propertyName) {
for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
if (pd.getName().equals(propertyName)) {
assertThat(propertyName + " property is not indexed", pd, instanceOf(IndexedPropertyDescriptor.class));
return ((IndexedPropertyDescriptor)pd).getIndexedReadMethod() != null;
}
}
return false;
}
@Test
public void reproSpr8806_y() throws IntrospectionException, SecurityException, NoSuchMethodException {
Introspector.getBeanInfo(LawLibrary.class);
}
@Ignore @Test
public void reproSpr8806_x() throws IntrospectionException, SecurityException, NoSuchMethodException {
BeanInfo info = Introspector.getBeanInfo(LawLibrary.class);
for (PropertyDescriptor d : info.getPropertyDescriptors()) {
if (d.getName().equals("book")) {
Method readMethod = d.getReadMethod();
Method writeMethod = d.getWriteMethod();
System.out.println(format("READ : %s.%s (bridge:%s)",
readMethod.getDeclaringClass().getSimpleName(), readMethod.getName(), readMethod.isBridge()));
System.out.println(format("WRITE: %s.%s (bridge:%s)",
writeMethod.getDeclaringClass().getSimpleName(), writeMethod.getName(), writeMethod.isBridge()));
new PropertyDescriptor("book", readMethod, writeMethod);
}
}
Method readMethod = LawLibrary.class.getMethod("getBook");
Method writeMethod = LawLibrary.class.getMethod("setBook", Book.class);
System.out.println(format("read : %s.%s (bridge:%s)",
readMethod.getDeclaringClass().getSimpleName(), readMethod.getName(), readMethod.isBridge()));
System.out.println(format("write: %s.%s (bridge:%s)",
writeMethod.getDeclaringClass().getSimpleName(), writeMethod.getName(), writeMethod.isBridge()));
System.out.println("--------");
for (Method m : LawLibrary.class.getMethods()) {
if (m.getDeclaringClass() == Object.class) continue;
System.out.println(format("%s %s.%s(%s) [bridge:%s]",
m.getReturnType().getSimpleName(), m.getDeclaringClass().getSimpleName(),
m.getName(),
m.getParameterTypes().length == 1 ? m.getParameterTypes()[0].getSimpleName() : "",
m.isBridge()));
}
//new ExtendedBeanInfo(info);
}
@Test
public void reproSpr8806() throws IntrospectionException {
BeanInfo bi = Introspector.getBeanInfo(LawLibrary.class);
new ExtendedBeanInfo(bi); // throws
}
interface Book { }
interface TextBook extends Book { }
interface LawBook extends TextBook { }
interface BookOperations {
Book getBook();
void setBook(Book book);
}
interface TextBookOperations extends BookOperations {
TextBook getBook();
}
abstract class Library {
public Book getBook() { return null; }
public void setBook(Book book) { }
}
class LawLibrary extends Library implements TextBookOperations {
public LawBook getBook() { return null; }
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright 2002-2008 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.beans;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Tests for {@link MutablePropertyValues}.
*
* @author Rod Johnson
* @author Chris Beams
*/
public final class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
@Test
public void testValid() throws Exception {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("forname", "Tony"));
pvs.addPropertyValue(new PropertyValue("surname", "Blair"));
pvs.addPropertyValue(new PropertyValue("age", "50"));
doTestTony(pvs);
MutablePropertyValues deepCopy = new MutablePropertyValues(pvs);
doTestTony(deepCopy);
deepCopy.setPropertyValueAt(new PropertyValue("name", "Gordon"), 0);
doTestTony(pvs);
assertEquals("Gordon", deepCopy.getPropertyValue("name").getValue());
}
@Test
public void testAddOrOverride() throws Exception {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("forname", "Tony"));
pvs.addPropertyValue(new PropertyValue("surname", "Blair"));
pvs.addPropertyValue(new PropertyValue("age", "50"));
doTestTony(pvs);
PropertyValue addedPv = new PropertyValue("rod", "Rod");
pvs.addPropertyValue(addedPv);
assertTrue(pvs.getPropertyValue("rod").equals(addedPv));
PropertyValue changedPv = new PropertyValue("forname", "Greg");
pvs.addPropertyValue(changedPv);
assertTrue(pvs.getPropertyValue("forname").equals(changedPv));
}
@Test
public void testChangesOnEquals() throws Exception {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("forname", "Tony"));
pvs.addPropertyValue(new PropertyValue("surname", "Blair"));
pvs.addPropertyValue(new PropertyValue("age", "50"));
MutablePropertyValues pvs2 = pvs;
PropertyValues changes = pvs2.changesSince(pvs);
assertTrue("changes are empty", changes.getPropertyValues().length == 0);
}
@Test
public void testChangeOfOneField() throws Exception {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("forname", "Tony"));
pvs.addPropertyValue(new PropertyValue("surname", "Blair"));
pvs.addPropertyValue(new PropertyValue("age", "50"));
MutablePropertyValues pvs2 = new MutablePropertyValues(pvs);
PropertyValues changes = pvs2.changesSince(pvs);
assertTrue("changes are empty, not of length " + changes.getPropertyValues().length,
changes.getPropertyValues().length == 0);
pvs2.addPropertyValue(new PropertyValue("forname", "Gordon"));
changes = pvs2.changesSince(pvs);
assertEquals("1 change", 1, changes.getPropertyValues().length);
PropertyValue fn = changes.getPropertyValue("forname");
assertTrue("change is forname", fn != null);
assertTrue("new value is gordon", fn.getValue().equals("Gordon"));
MutablePropertyValues pvs3 = new MutablePropertyValues(pvs);
changes = pvs3.changesSince(pvs);
assertTrue("changes are empty, not of length " + changes.getPropertyValues().length,
changes.getPropertyValues().length == 0);
// add new
pvs3.addPropertyValue(new PropertyValue("foo", "bar"));
pvs3.addPropertyValue(new PropertyValue("fi", "fum"));
changes = pvs3.changesSince(pvs);
assertTrue("2 change", changes.getPropertyValues().length == 2);
fn = changes.getPropertyValue("foo");
assertTrue("change in foo", fn != null);
assertTrue("new value is bar", fn.getValue().equals("bar"));
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2002-2008 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.beans;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
/**
* @author Juergen Hoeller
* @author Chris Beams
*/
public final class PropertyAccessorUtilsTests {
@Test
public void testCanonicalPropertyName() {
assertEquals("map", PropertyAccessorUtils.canonicalPropertyName("map"));
assertEquals("map[key1]", PropertyAccessorUtils.canonicalPropertyName("map[key1]"));
assertEquals("map[key1]", PropertyAccessorUtils.canonicalPropertyName("map['key1']"));
assertEquals("map[key1]", PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"]"));
assertEquals("map[key1][key2]", PropertyAccessorUtils.canonicalPropertyName("map[key1][key2]"));
assertEquals("map[key1][key2]", PropertyAccessorUtils.canonicalPropertyName("map['key1'][\"key2\"]"));
assertEquals("map[key1].name", PropertyAccessorUtils.canonicalPropertyName("map[key1].name"));
assertEquals("map[key1].name", PropertyAccessorUtils.canonicalPropertyName("map['key1'].name"));
assertEquals("map[key1].name", PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"].name"));
}
@Test
public void testCanonicalPropertyNames() {
String[] original =
new String[] {"map", "map[key1]", "map['key1']", "map[\"key1\"]", "map[key1][key2]",
"map['key1'][\"key2\"]", "map[key1].name", "map['key1'].name", "map[\"key1\"].name"};
String[] canonical =
new String[] {"map", "map[key1]", "map[key1]", "map[key1]", "map[key1][key2]",
"map[key1][key2]", "map[key1].name", "map[key1].name", "map[key1].name"};
assertTrue(Arrays.equals(canonical, PropertyAccessorUtils.canonicalPropertyNames(original)));
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2002-2008 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.beans.annotation;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.wiring.BeanWiringInfo;
/**
* @author Rick Evans
* @author Chris Beams
*/
public final class AnnotationBeanWiringInfoResolverTests {
@Test
public void testResolveWiringInfo() throws Exception {
try {
new AnnotationBeanWiringInfoResolver().resolveWiringInfo(null);
fail("Must have thrown an IllegalArgumentException by this point (null argument)");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testResolveWiringInfoWithAnInstanceOfANonAnnotatedClass() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo("java.lang.String is not @Configurable");
assertNull("Must be returning null for a non-@Configurable class instance", info);
}
@Test
public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClass() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo(new Soap());
assertNotNull("Must *not* be returning null for a non-@Configurable class instance", info);
}
@Test
public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitly() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo(new WirelessSoap());
assertNotNull("Must *not* be returning null for an @Configurable class instance even when autowiring is NO", info);
assertFalse(info.indicatesAutowiring());
assertEquals(WirelessSoap.class.getName(), info.getBeanName());
}
@Test
public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitlyAndCustomBeanName() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo(new NamedWirelessSoap());
assertNotNull("Must *not* be returning null for an @Configurable class instance even when autowiring is NO", info);
assertFalse(info.indicatesAutowiring());
assertEquals("DerBigStick", info.getBeanName());
}
@Configurable()
private static class Soap {
}
@Configurable(autowire = Autowire.NO)
private static class WirelessSoap {
}
@Configurable(autowire = Autowire.NO, value = "DerBigStick")
private static class NamedWirelessSoap {
}
}

View File

@@ -0,0 +1,193 @@
/*
* Copyright 2002-2008 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.beans.annotation;
import static org.junit.Assert.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
/**
* @author Rob Harrop
* @author Chris Beams
* @since 2.0
*/
public final class RequiredAnnotationBeanPostProcessorTests {
@Test
public void testWithRequiredPropertyOmitted() {
try {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.addPropertyValue("name", "Rob Harrop")
.addPropertyValue("favouriteColour", "Blue")
.addPropertyValue("jobTitle", "Grand Poobah")
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
String message = ex.getCause().getMessage();
assertTrue(message.indexOf("Property") > -1);
assertTrue(message.indexOf("age") > -1);
assertTrue(message.indexOf("testBean") > -1);
}
}
@Test
public void testWithThreeRequiredPropertiesOmitted() {
try {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.addPropertyValue("name", "Rob Harrop")
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
String message = ex.getCause().getMessage();
assertTrue(message.indexOf("Properties") > -1);
assertTrue(message.indexOf("age") > -1);
assertTrue(message.indexOf("favouriteColour") > -1);
assertTrue(message.indexOf("jobTitle") > -1);
assertTrue(message.indexOf("testBean") > -1);
}
}
@Test
public void testWithOnlyRequiredPropertiesSpecified() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.addPropertyValue("age", "24")
.addPropertyValue("favouriteColour", "Blue")
.addPropertyValue("jobTitle", "Grand Poobah")
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons();
RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean");
assertEquals(24, bean.getAge());
assertEquals("Blue", bean.getFavouriteColour());
}
@Test
public void testWithCustomAnnotation() {
try {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
RequiredAnnotationBeanPostProcessor rabpp = new RequiredAnnotationBeanPostProcessor();
rabpp.setRequiredAnnotationType(MyRequired.class);
factory.addBeanPostProcessor(rabpp);
factory.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
String message = ex.getCause().getMessage();
assertTrue(message.indexOf("Property") > -1);
assertTrue(message.indexOf("name") > -1);
assertTrue(message.indexOf("testBean") > -1);
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyRequired {
}
class RequiredTestBean implements BeanNameAware, BeanFactoryAware {
private String name;
private int age;
private String favouriteColour;
private String jobTitle;
public int getAge() {
return age;
}
@Required
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
@MyRequired
public void setName(String name) {
this.name = name;
}
public String getFavouriteColour() {
return favouriteColour;
}
@Required
public void setFavouriteColour(String favouriteColour) {
this.favouriteColour = favouriteColour;
}
public String getJobTitle() {
return jobTitle;
}
@Required
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
@Required
public void setBeanName(String name) {
}
@Required
public void setBeanFactory(BeanFactory beanFactory) {
}
}

View File

@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="a" class="java.lang.Object" />
<bean id="b" class="java.lang.Integer">
<constructor-arg value="50" />
</bean>
<bean id="c" class="java.lang.String">
<constructor-arg ref="b" />
</bean>
<bean id="int" class="java.lang.Integer">
<constructor-arg ref="c" />
</bean>
<bean id="long" class="java.lang.Long">
<constructor-arg ref="c" />
</bean>
<bean id="buffer" class="java.lang.StringBuffer">
<constructor-arg ref="int" />
</bean>
<bean id="thread" class="java.lang.Thread"/>
<bean id="field" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="targetObject" ref="thread"/>
<property name="targetField" value="MAX_PRIORITY"/>
</bean>
<bean id="secondBuffer" class="java.lang.StringBuffer">
<constructor-arg ref="field"/>
</bean>
</beans>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="test3" class="test.beans.TestBean" scope="prototype">
<property name="name"><value>custom</value></property>
<property name="age"><value>25</value></property>
</bean>
</beans>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- Simple target -->
<bean id="test" class="test.beans.TestBean">
<property name="name"><value>custom</value></property>
<property name="age"><value>666</value></property>
</bean>
<!--
Check that invoker is automatically added to wrap target.
Non pointcut bean name should be wrapped in invoker.
-->
<bean id="numberTestBean" class="test.beans.NumberTestBean"/>
</beans>

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!--
Just included for the count: not to mean anything in particular
-->
<bean id="something" class="test.beans.GenericIntegerBean"/>
<bean id="indexedBean" class="test.beans.IndexedTestBean"/>
<!-- Overridden by next factory -->
<bean id="test" class="test.beans.TestBean">
<property name="name"><value>custom</value></property>
<property name="age"><value>25</value></property>
</bean>
<bean id="testFactory1" class="test.beans.DummyFactory"/>
<bean id="testFactory2" class="test.beans.DummyFactory">
<property name="singleton"><value>false</value></property>
</bean>
</beans>

View File

@@ -0,0 +1,300 @@
/*
* Copyright 2002-2008 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.beans.factory;
import static org.junit.Assert.*;
import static test.util.TestResourceUtils.qualifiedResource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import net.sf.cglib.proxy.NoOp;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.util.ObjectUtils;
import test.beans.DummyFactory;
import test.beans.ITestBean;
import test.beans.IndexedTestBean;
import test.beans.TestBean;
/**
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
* @since 04.07.2003
*/
public final class BeanFactoryUtilsTests {
private static final Class<?> CLASS = BeanFactoryUtilsTests.class;
private static final Resource ROOT_CONTEXT = qualifiedResource(CLASS, "root.xml");
private static final Resource MIDDLE_CONTEXT = qualifiedResource(CLASS, "middle.xml");
private static final Resource LEAF_CONTEXT = qualifiedResource(CLASS, "leaf.xml");
private static final Resource DEPENDENT_BEANS_CONTEXT = qualifiedResource(CLASS, "dependentBeans.xml");
private ConfigurableListableBeanFactory listableBeanFactory;
private ConfigurableListableBeanFactory dependentBeansBF;
@Before
public void setUp() {
// Interesting hierarchical factory to test counts.
// Slow to read so we cache it.
XmlBeanFactory grandParent = new XmlBeanFactory(ROOT_CONTEXT);
XmlBeanFactory parent = new XmlBeanFactory(MIDDLE_CONTEXT, grandParent);
XmlBeanFactory child = new XmlBeanFactory(LEAF_CONTEXT, parent);
this.dependentBeansBF = new XmlBeanFactory(DEPENDENT_BEANS_CONTEXT);
dependentBeansBF.preInstantiateSingletons();
this.listableBeanFactory = child;
}
@Test
public void testHierarchicalCountBeansWithNonHierarchicalFactory() {
StaticListableBeanFactory lbf = new StaticListableBeanFactory();
lbf.addBean("t1", new TestBean());
lbf.addBean("t2", new TestBean());
assertTrue(BeanFactoryUtils.countBeansIncludingAncestors(lbf) == 2);
}
/**
* Check that override doesn't count as two separate beans.
*/
@Test
public void testHierarchicalCountBeansWithOverride() throws Exception {
// Leaf count
assertTrue(this.listableBeanFactory.getBeanDefinitionCount() == 1);
// Count minus duplicate
assertTrue("Should count 7 beans, not "
+ BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory),
BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory) == 7);
}
@Test
public void testHierarchicalNamesWithNoMatch() throws Exception {
List<String> names = Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory,
NoOp.class));
assertEquals(0, names.size());
}
@Test
public void testHierarchicalNamesWithMatchOnlyInRoot() throws Exception {
List<String> names = Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory,
IndexedTestBean.class));
assertEquals(1, names.size());
assertTrue(names.contains("indexedBean"));
// Distinguish from default ListableBeanFactory behavior
assertTrue(listableBeanFactory.getBeanNamesForType(IndexedTestBean.class).length == 0);
}
@Test
public void testGetBeanNamesForTypeWithOverride() throws Exception {
List<String> names = Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory,
ITestBean.class));
// includes 2 TestBeans from FactoryBeans (DummyFactory definitions)
assertEquals(4, names.size());
assertTrue(names.contains("test"));
assertTrue(names.contains("test3"));
assertTrue(names.contains("testFactory1"));
assertTrue(names.contains("testFactory2"));
}
@Test
public void testNoBeansOfType() {
StaticListableBeanFactory lbf = new StaticListableBeanFactory();
lbf.addBean("foo", new Object());
Map<?, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, false);
assertTrue(beans.isEmpty());
}
@Test
public void testFindsBeansOfTypeWithStaticFactory() {
StaticListableBeanFactory lbf = new StaticListableBeanFactory();
TestBean t1 = new TestBean();
TestBean t2 = new TestBean();
DummyFactory t3 = new DummyFactory();
DummyFactory t4 = new DummyFactory();
t4.setSingleton(false);
lbf.addBean("t1", t1);
lbf.addBean("t2", t2);
lbf.addBean("t3", t3);
lbf.addBean("t4", t4);
Map<?, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, false);
assertEquals(2, beans.size());
assertEquals(t1, beans.get("t1"));
assertEquals(t2, beans.get("t2"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, false, true);
assertEquals(3, beans.size());
assertEquals(t1, beans.get("t1"));
assertEquals(t2, beans.get("t2"));
assertEquals(t3.getObject(), beans.get("t3"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, true);
assertEquals(4, beans.size());
assertEquals(t1, beans.get("t1"));
assertEquals(t2, beans.get("t2"));
assertEquals(t3.getObject(), beans.get("t3"));
assertTrue(beans.get("t4") instanceof TestBean);
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, DummyFactory.class, true, true);
assertEquals(2, beans.size());
assertEquals(t3, beans.get("&t3"));
assertEquals(t4, beans.get("&t4"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, FactoryBean.class, true, true);
assertEquals(2, beans.size());
assertEquals(t3, beans.get("&t3"));
assertEquals(t4, beans.get("&t4"));
}
@Test
public void testFindsBeansOfTypeWithDefaultFactory() {
Object test3 = this.listableBeanFactory.getBean("test3");
Object test = this.listableBeanFactory.getBean("test");
TestBean t1 = new TestBean();
TestBean t2 = new TestBean();
DummyFactory t3 = new DummyFactory();
DummyFactory t4 = new DummyFactory();
t4.setSingleton(false);
this.listableBeanFactory.registerSingleton("t1", t1);
this.listableBeanFactory.registerSingleton("t2", t2);
this.listableBeanFactory.registerSingleton("t3", t3);
this.listableBeanFactory.registerSingleton("t4", t4);
Map<?, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true,
false);
assertEquals(6, beans.size());
assertEquals(test3, beans.get("test3"));
assertEquals(test, beans.get("test"));
assertEquals(t1, beans.get("t1"));
assertEquals(t2, beans.get("t2"));
assertEquals(t3.getObject(), beans.get("t3"));
assertTrue(beans.get("t4") instanceof TestBean);
// t3 and t4 are found here as of Spring 2.0, since they are
// pre-registered
// singleton instances, while testFactory1 and testFactory are *not*
// found
// because they are FactoryBean definitions that haven't been
// initialized yet.
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true);
Object testFactory1 = this.listableBeanFactory.getBean("testFactory1");
assertEquals(5, beans.size());
assertEquals(test, beans.get("test"));
assertEquals(testFactory1, beans.get("testFactory1"));
assertEquals(t1, beans.get("t1"));
assertEquals(t2, beans.get("t2"));
assertEquals(t3.getObject(), beans.get("t3"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, true);
assertEquals(8, beans.size());
assertEquals(test3, beans.get("test3"));
assertEquals(test, beans.get("test"));
assertEquals(testFactory1, beans.get("testFactory1"));
assertTrue(beans.get("testFactory2") instanceof TestBean);
assertEquals(t1, beans.get("t1"));
assertEquals(t2, beans.get("t2"));
assertEquals(t3.getObject(), beans.get("t3"));
assertTrue(beans.get("t4") instanceof TestBean);
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, DummyFactory.class, true, true);
assertEquals(4, beans.size());
assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1"));
assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2"));
assertEquals(t3, beans.get("&t3"));
assertEquals(t4, beans.get("&t4"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, FactoryBean.class, true, true);
assertEquals(4, beans.size());
assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1"));
assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2"));
assertEquals(t3, beans.get("&t3"));
assertEquals(t4, beans.get("&t4"));
}
@Test
public void testHierarchicalResolutionWithOverride() throws Exception {
Object test3 = this.listableBeanFactory.getBean("test3");
Object test = this.listableBeanFactory.getBean("test");
Map<?, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true,
false);
assertEquals(2, beans.size());
assertEquals(test3, beans.get("test3"));
assertEquals(test, beans.get("test"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, false);
assertEquals(1, beans.size());
assertEquals(test, beans.get("test"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true);
Object testFactory1 = this.listableBeanFactory.getBean("testFactory1");
assertEquals(2, beans.size());
assertEquals(test, beans.get("test"));
assertEquals(testFactory1, beans.get("testFactory1"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, true);
assertEquals(4, beans.size());
assertEquals(test3, beans.get("test3"));
assertEquals(test, beans.get("test"));
assertEquals(testFactory1, beans.get("testFactory1"));
assertTrue(beans.get("testFactory2") instanceof TestBean);
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, DummyFactory.class, true, true);
assertEquals(2, beans.size());
assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1"));
assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, FactoryBean.class, true, true);
assertEquals(2, beans.size());
assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1"));
assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2"));
}
@Test
public void testADependencies() {
String[] deps = this.dependentBeansBF.getDependentBeans("a");
assertTrue(ObjectUtils.isEmpty(deps));
}
@Test
public void testBDependencies() {
String[] deps = this.dependentBeansBF.getDependentBeans("b");
assertTrue(Arrays.equals(new String[] { "c" }, deps));
}
@Test
public void testCDependencies() {
String[] deps = this.dependentBeansBF.getDependentBeans("c");
assertTrue(Arrays.equals(new String[] { "int", "long" }, deps));
}
@Test
public void testIntDependencies() {
String[] deps = this.dependentBeansBF.getDependentBeans("int");
assertTrue(Arrays.equals(new String[] { "buffer" }, deps));
}
}

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="bean1" class="org.springframework.beans.factory.ConcurrentBeanFactoryTests$ConcurrentBean"
scope="prototype">
<property name="date" value="2004/08/08"/>
</bean>
<bean id="bean2" class="org.springframework.beans.factory.ConcurrentBeanFactoryTests$ConcurrentBean"
scope="prototype">
<property name="date" value="2000/02/02"/>
</bean>
</beans>

View File

@@ -0,0 +1,160 @@
/*
* Copyright 2002-2008 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.beans.factory;
import static org.junit.Assert.*;
import static test.util.TestResourceUtils.qualifiedResource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.io.Resource;
/**
* @author Guillaume Poirier
* @author Juergen Hoeller
* @author Chris Beams
* @since 10.03.2004
*/
public final class ConcurrentBeanFactoryTests {
private static final Log logger = LogFactory.getLog(ConcurrentBeanFactoryTests.class);
private static final Resource CONTEXT = qualifiedResource(ConcurrentBeanFactoryTests.class, "context.xml");
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");
private static final Date DATE_1, DATE_2;
static {
try {
DATE_1 = DATE_FORMAT.parse("2004/08/08");
DATE_2 = DATE_FORMAT.parse("2000/02/02");
}
catch (ParseException e) {
throw new RuntimeException(e);
}
}
private BeanFactory factory;
private final Set<TestRun> set = Collections.synchronizedSet(new HashSet<TestRun>());
private Throwable ex = null;
@Before
public void setUp() throws Exception {
XmlBeanFactory factory = new XmlBeanFactory(CONTEXT);
factory.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor((DateFormat) DATE_FORMAT.clone(), false));
}
});
this.factory = factory;
}
@Test
public void testSingleThread() {
for (int i = 0; i < 100; i++) {
performTest();
}
}
@Test
public void testConcurrent() {
for (int i = 0; i < 100; i++) {
TestRun run = new TestRun();
run.setDaemon(true);
set.add(run);
}
for (Iterator<TestRun> it = new HashSet<TestRun>(set).iterator(); it.hasNext();) {
TestRun run = it.next();
run.start();
}
logger.info("Thread creation over, " + set.size() + " still active.");
synchronized (set) {
while (!set.isEmpty() && ex == null) {
try {
set.wait();
}
catch (InterruptedException e) {
logger.info(e.toString());
}
logger.info(set.size() + " threads still active.");
}
}
if (ex != null) {
fail(ex.getMessage());
}
}
private void performTest() {
ConcurrentBean b1 = (ConcurrentBean) factory.getBean("bean1");
ConcurrentBean b2 = (ConcurrentBean) factory.getBean("bean2");
assertEquals(b1.getDate(), DATE_1);
assertEquals(b2.getDate(), DATE_2);
}
private class TestRun extends Thread {
public void run() {
try {
for (int i = 0; i < 10000; i++) {
performTest();
}
}
catch (Throwable e) {
ex = e;
}
finally {
synchronized (set) {
set.remove(this);
set.notifyAll();
}
}
}
}
public static class ConcurrentBean {
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
}

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="fooFactory" class="org.springframework.beans.factory.FooFactoryBean"/>
</beans>

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2002-2010 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.beans.factory;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
/**
* Written with the intention of reproducing SPR-7318.
*
* @author Chris Beams
*/
public class FactoryBeanLookupTests {
private BeanFactory beanFactory;
@Before
public void setUp() {
beanFactory = new XmlBeanFactory(
new ClassPathResource("FactoryBeanLookupTests-context.xml", this.getClass()));
}
@Test
public void factoryBeanLookupByNameDereferencing() {
Object fooFactory = beanFactory.getBean("&fooFactory");
assertThat(fooFactory, instanceOf(FooFactoryBean.class));
}
@Test
public void factoryBeanLookupByType() {
FooFactoryBean fooFactory = beanFactory.getBean(FooFactoryBean.class);
assertNotNull(fooFactory);
}
@Test
public void factoryBeanLookupByTypeAndNameDereference() {
FooFactoryBean fooFactory = beanFactory.getBean("&fooFactory", FooFactoryBean.class);
assertNotNull(fooFactory);
}
@Test
public void factoryBeanObjectLookupByName() {
Object fooFactory = beanFactory.getBean("fooFactory");
assertThat(fooFactory, instanceOf(Foo.class));
}
@Test
public void factoryBeanObjectLookupByNameAndType() {
Foo foo = beanFactory.getBean("fooFactory", Foo.class);
assertNotNull(foo);
}
}
class FooFactoryBean extends AbstractFactoryBean<Foo> {
@Override
protected Foo createInstance() throws Exception {
return new Foo();
}
@Override
public Class<?> getObjectType() {
return Foo.class;
}
}
class Foo { }

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="factoryBean" class="org.springframework.beans.factory.FactoryBeanTests$NullReturningFactoryBean"/>
</beans>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans default-lazy-init="true">
<bean name="beta" class="org.springframework.beans.factory.FactoryBeanTests$Beta" autowire="byType">
<property name="name" value="${myName}"/>
</bean>
<bean id="alpha" class="org.springframework.beans.factory.FactoryBeanTests$Alpha" autowire="byType"/>
<bean id="gamma" class="org.springframework.beans.factory.FactoryBeanTests$Gamma"/>
<bean id="betaFactory" class="org.springframework.beans.factory.FactoryBeanTests$BetaFactoryBean">
<property name="beta" ref="beta"/>
</bean>
<bean id="gammaFactory" factory-bean="betaFactory" factory-method="getGamma"/>
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties">
<props>
<prop key="myName">yourName</prop>
</props>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,165 @@
/*
* Copyright 2002-2008 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.beans.factory;
import static org.junit.Assert.*;
import static test.util.TestResourceUtils.qualifiedResource;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
/**
* @author Rob Harrop
* @author Juergen Hoeller
* @author Chris Beams
*/
public final class FactoryBeanTests {
private static final Class<?> CLASS = FactoryBeanTests.class;
private static final Resource RETURNS_NULL_CONTEXT = qualifiedResource(CLASS, "returnsNull.xml");
private static final Resource WITH_AUTOWIRING_CONTEXT = qualifiedResource(CLASS, "withAutowiring.xml");
@Test
public void testFactoryBeanReturnsNull() throws Exception {
XmlBeanFactory factory = new XmlBeanFactory(RETURNS_NULL_CONTEXT);
Object result = factory.getBean("factoryBean");
assertNull(result);
}
@Test
public void testFactoryBeansWithAutowiring() throws Exception {
XmlBeanFactory factory = new XmlBeanFactory(WITH_AUTOWIRING_CONTEXT);
BeanFactoryPostProcessor ppc = (BeanFactoryPostProcessor) factory.getBean("propertyPlaceholderConfigurer");
ppc.postProcessBeanFactory(factory);
Alpha alpha = (Alpha) factory.getBean("alpha");
Beta beta = (Beta) factory.getBean("beta");
Gamma gamma = (Gamma) factory.getBean("gamma");
Gamma gamma2 = (Gamma) factory.getBean("gammaFactory");
assertSame(beta, alpha.getBeta());
assertSame(gamma, beta.getGamma());
assertSame(gamma2, beta.getGamma());
assertEquals("yourName", beta.getName());
}
@Test
public void testFactoryBeansWithIntermediateFactoryBeanAutowiringFailure() throws Exception {
XmlBeanFactory factory = new XmlBeanFactory(WITH_AUTOWIRING_CONTEXT);
BeanFactoryPostProcessor ppc = (BeanFactoryPostProcessor) factory.getBean("propertyPlaceholderConfigurer");
ppc.postProcessBeanFactory(factory);
Beta beta = (Beta) factory.getBean("beta");
Alpha alpha = (Alpha) factory.getBean("alpha");
Gamma gamma = (Gamma) factory.getBean("gamma");
assertSame(beta, alpha.getBeta());
assertSame(gamma, beta.getGamma());
}
public static class NullReturningFactoryBean implements FactoryBean<Object> {
public Object getObject() {
return null;
}
public Class<?> getObjectType() {
return null;
}
public boolean isSingleton() {
return true;
}
}
public static class Alpha implements InitializingBean {
private Beta beta;
public void setBeta(Beta beta) {
this.beta = beta;
}
public Beta getBeta() {
return beta;
}
public void afterPropertiesSet() {
Assert.notNull(beta, "'beta' property is required");
}
}
public static class Beta implements InitializingBean {
private Gamma gamma;
private String name;
public void setGamma(Gamma gamma) {
this.gamma = gamma;
}
public Gamma getGamma() {
return gamma;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void afterPropertiesSet() {
Assert.notNull(gamma, "'gamma' property is required");
}
}
public static class Gamma {
}
public static class BetaFactoryBean implements FactoryBean<Object> {
private Beta beta;
public void setBeta(Beta beta) {
this.beta = beta;
}
public Object getObject() {
return this.beta;
}
public Class<?> getObjectType() {
return null;
}
public boolean isSingleton() {
return true;
}
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2002-2008 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.beans.factory;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import test.beans.DerivedTestBean;
import test.beans.TestBean;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @since 04.07.2006
*/
public final class SharedBeanRegistryTests {
@Test
public void testSingletons() {
DefaultSingletonBeanRegistry beanRegistry = new DefaultSingletonBeanRegistry();
TestBean tb = new TestBean();
beanRegistry.registerSingleton("tb", tb);
assertSame(tb, beanRegistry.getSingleton("tb"));
TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", new ObjectFactory<Object>() {
public Object getObject() throws BeansException {
return new TestBean();
}
});
assertSame(tb2, beanRegistry.getSingleton("tb2"));
assertSame(tb, beanRegistry.getSingleton("tb"));
assertSame(tb2, beanRegistry.getSingleton("tb2"));
assertEquals(2, beanRegistry.getSingletonCount());
assertEquals(2, beanRegistry.getSingletonNames().length);
assertTrue(Arrays.asList(beanRegistry.getSingletonNames()).contains("tb"));
assertTrue(Arrays.asList(beanRegistry.getSingletonNames()).contains("tb2"));
beanRegistry.destroySingletons();
assertEquals(0, beanRegistry.getSingletonCount());
assertEquals(0, beanRegistry.getSingletonNames().length);
}
@Test
public void testDisposableBean() {
DefaultSingletonBeanRegistry beanRegistry = new DefaultSingletonBeanRegistry();
DerivedTestBean tb = new DerivedTestBean();
beanRegistry.registerSingleton("tb", tb);
beanRegistry.registerDisposableBean("tb", tb);
assertSame(tb, beanRegistry.getSingleton("tb"));
assertSame(tb, beanRegistry.getSingleton("tb"));
assertEquals(1, beanRegistry.getSingletonCount());
assertEquals(1, beanRegistry.getSingletonNames().length);
assertTrue(Arrays.asList(beanRegistry.getSingletonNames()).contains("tb"));
assertFalse(tb.wasDestroyed());
beanRegistry.destroySingletons();
assertEquals(0, beanRegistry.getSingletonCount());
assertEquals(0, beanRegistry.getSingletonNames().length);
assertTrue(tb.wasDestroyed());
}
}

View File

@@ -0,0 +1,93 @@
package org.springframework.beans.factory;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
/**
* SPR-5475 exposed the fact that the error message displayed when incorrectly
* invoking a factory method is not instructive to the user and rather misleading.
*
* @author Chris Beams
*/
public class Spr5475Tests {
@Test
public void noArgFactoryMethodInvokedWithOneArg() {
assertExceptionMessageForMisconfiguredFactoryMethod(
rootBeanDefinition(Foo.class)
.setFactoryMethod("noArgFactory")
.addConstructorArgValue("bogusArg").getBeanDefinition(),
"Error creating bean with name 'foo': No matching factory method found: factory method 'noArgFactory(String)'. " +
"Check that a method with the specified name and arguments exists and that it is static.");
}
@Test
public void noArgFactoryMethodInvokedWithTwoArgs() {
assertExceptionMessageForMisconfiguredFactoryMethod(
rootBeanDefinition(Foo.class)
.setFactoryMethod("noArgFactory")
.addConstructorArgValue("bogusArg1")
.addConstructorArgValue("bogusArg2".getBytes()).getBeanDefinition(),
"Error creating bean with name 'foo': No matching factory method found: factory method 'noArgFactory(String,byte[])'. " +
"Check that a method with the specified name and arguments exists and that it is static.");
}
@Test
public void noArgFactoryMethodInvokedWithTwoArgsAndTypesSpecified() {
RootBeanDefinition def = new RootBeanDefinition(Foo.class);
def.setFactoryMethodName("noArgFactory");
ConstructorArgumentValues cav = new ConstructorArgumentValues();
cav.addIndexedArgumentValue(0, "bogusArg1", CharSequence.class.getName());
cav.addIndexedArgumentValue(1, "bogusArg2".getBytes());
def.setConstructorArgumentValues(cav);
assertExceptionMessageForMisconfiguredFactoryMethod(
def,
"Error creating bean with name 'foo': No matching factory method found: factory method 'noArgFactory(CharSequence,byte[])'. " +
"Check that a method with the specified name and arguments exists and that it is static.");
}
private void assertExceptionMessageForMisconfiguredFactoryMethod(BeanDefinition bd, String expectedMessage) {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("foo", bd);
try {
factory.preInstantiateSingletons();
fail("should have failed with BeanCreationException due to incorrectly invoked factory method");
} catch (BeanCreationException ex) {
assertThat(ex.getMessage(), equalTo(expectedMessage));
}
}
@Test
public void singleArgFactoryMethodInvokedWithNoArgs() {
// calling a factory method that accepts arguments without any arguments emits an exception unlike cases
// where a no-arg factory method is called with arguments. Adding this test just to document the difference
assertExceptionMessageForMisconfiguredFactoryMethod(
rootBeanDefinition(Foo.class)
.setFactoryMethod("singleArgFactory").getBeanDefinition(),
"Error creating bean with name 'foo': " +
"Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.String]: " +
"Ambiguous factory method argument types - did you specify the correct bean references as factory method arguments?");
}
static class Foo {
static Foo noArgFactory() {
return new Foo();
}
static Foo singleArgFactory(String arg) {
return new Foo();
}
}
}

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: beans1.xml,v 1.3 2006/08/20 19:08:40 jhoeller Exp $ -->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="beans1.bean1" class="org.springframework.beans.factory.access.TestBean">
<property name="name"><value>beans1.bean1</value></property>
</bean>
<bean id="beans1.bean2" class="org.springframework.beans.factory.access.TestBean">
<property name="name"><value>bean2</value></property>
<property name="objRef"><ref bean="beans1.bean2"/></property>
</bean>
</beans>

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: beans2.xml,v 1.3 2006/08/20 19:08:40 jhoeller Exp $ -->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="beans2.bean1" class="org.springframework.beans.factory.access.TestBean">
<property name="name"><value>beans2.bean1</value></property>
</bean>
<bean id="beans2.bean2" class="org.springframework.beans.factory.access.TestBean">
<property name="name"><value>beans2.bean2</value></property>
<property name="objRef"><ref bean="beans1.bean1"/></property>
</bean>
</beans>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<!-- We are only using one definition file for the purposes of this test, since we do not have multiple
classloaders available in the environment to allow combining multiple files of the same name, but
of course the contents within could be spread out across multiple files of the same name withing
different jars -->
<beans>
<!-- this definition could be inside one beanRefFactory.xml file -->
<bean id="a.qualified.name.of.some.sort"
class="org.springframework.beans.factory.xml.XmlBeanFactory">
<constructor-arg value="org/springframework/beans/factory/access/SingletonBeanFactoryLocatorTests-beans1.xml"/>
</bean>
<!-- while the following two could be inside another, also on the classpath,
perhaps coming from another component jar -->
<bean id="another.qualified.name"
class="org.springframework.beans.factory.xml.XmlBeanFactory">
<constructor-arg value="org/springframework/beans/factory/access/SingletonBeanFactoryLocatorTests-beans1.xml"/>
<constructor-arg ref="a.qualified.name.of.some.sort"/> <!-- parent bean factory -->
</bean>
<alias name="another.qualified.name" alias="a.qualified.name.which.is.an.alias"/>
</beans>

View File

@@ -0,0 +1,240 @@
/*
* Copyright 2002-2008 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.beans.factory.access;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.util.ClassUtils;
/**
* Unit tests for {@link SingletonBeanFactoryLocator}.
*
* @author Colin Sampaleanu
* @author Chris Beams
*/
public final class SingletonBeanFactoryLocatorTests {
private static final Class<?> CLASS = SingletonBeanFactoryLocatorTests.class;
private static final String REF1_XML = CLASS.getSimpleName() + "-ref1.xml";
@Test
public void testBasicFunctionality() {
SingletonBeanFactoryLocator facLoc = new SingletonBeanFactoryLocator(
"classpath*:" + ClassUtils.addResourcePathToPackagePath(CLASS, REF1_XML));
basicFunctionalityTest(facLoc);
}
/**
* Worker method so subclass can use it too.
*/
protected void basicFunctionalityTest(SingletonBeanFactoryLocator facLoc) {
BeanFactoryReference bfr = facLoc.useBeanFactory("a.qualified.name.of.some.sort");
BeanFactory fac = bfr.getFactory();
BeanFactoryReference bfr2 = facLoc.useBeanFactory("another.qualified.name");
fac = bfr2.getFactory();
// verify that the same instance is returned
TestBean tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("beans1.bean1"));
tb.setName("was beans1.bean1");
BeanFactoryReference bfr3 = facLoc.useBeanFactory("another.qualified.name");
fac = bfr3.getFactory();
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("was beans1.bean1"));
BeanFactoryReference bfr4 = facLoc.useBeanFactory("a.qualified.name.which.is.an.alias");
fac = bfr4.getFactory();
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("was beans1.bean1"));
// Now verify that we can call release in any order.
// Unfortunately this doesn't validate complete release after the last one.
bfr2.release();
bfr3.release();
bfr.release();
bfr4.release();
}
/**
* This test can run multiple times, but due to static keyed lookup of the locators,
* 2nd and subsequent calls will actuall get back same locator instance. This is not
* an issue really, since the contained beanfactories will still be loaded and released.
*/
@Test
public void testGetInstance() {
// Try with and without 'classpath*:' prefix, and with 'classpath:' prefix.
BeanFactoryLocator facLoc = SingletonBeanFactoryLocator.getInstance(
ClassUtils.addResourcePathToPackagePath(CLASS, REF1_XML));
getInstanceTest1(facLoc);
facLoc = SingletonBeanFactoryLocator.getInstance(
"classpath*:/" + ClassUtils.addResourcePathToPackagePath(CLASS, REF1_XML));
getInstanceTest2(facLoc);
// This will actually get another locator instance, as the key is the resource name.
facLoc = SingletonBeanFactoryLocator.getInstance(
"classpath:" + ClassUtils.addResourcePathToPackagePath(CLASS, REF1_XML));
getInstanceTest3(facLoc);
}
/**
* Worker method so subclass can use it too
*/
protected void getInstanceTest1(BeanFactoryLocator facLoc) {
BeanFactoryReference bfr = facLoc.useBeanFactory("a.qualified.name.of.some.sort");
BeanFactory fac = bfr.getFactory();
BeanFactoryReference bfr2 = facLoc.useBeanFactory("another.qualified.name");
fac = bfr2.getFactory();
// verify that the same instance is returned
TestBean tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("beans1.bean1"));
tb.setName("was beans1.bean1");
BeanFactoryReference bfr3 = facLoc.useBeanFactory("another.qualified.name");
fac = bfr3.getFactory();
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("was beans1.bean1"));
BeanFactoryReference bfr4 = facLoc.useBeanFactory("a.qualified.name.which.is.an.alias");
fac = bfr4.getFactory();
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("was beans1.bean1"));
bfr.release();
bfr3.release();
bfr2.release();
bfr4.release();
}
/**
* Worker method so subclass can use it too
*/
protected void getInstanceTest2(BeanFactoryLocator facLoc) {
BeanFactoryReference bfr;
BeanFactory fac;
BeanFactoryReference bfr2;
TestBean tb;
BeanFactoryReference bfr3;
BeanFactoryReference bfr4;
bfr = facLoc.useBeanFactory("a.qualified.name.of.some.sort");
fac = bfr.getFactory();
bfr2 = facLoc.useBeanFactory("another.qualified.name");
fac = bfr2.getFactory();
// verify that the same instance is returned
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("beans1.bean1"));
tb.setName("was beans1.bean1");
bfr3 = facLoc.useBeanFactory("another.qualified.name");
fac = bfr3.getFactory();
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("was beans1.bean1"));
bfr4 = facLoc.useBeanFactory("a.qualified.name.which.is.an.alias");
fac = bfr4.getFactory();
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("was beans1.bean1"));
bfr.release();
bfr2.release();
bfr4.release();
bfr3.release();
}
/**
* Worker method so subclass can use it too
*/
protected void getInstanceTest3(BeanFactoryLocator facLoc) {
BeanFactoryReference bfr;
BeanFactory fac;
BeanFactoryReference bfr2;
TestBean tb;
BeanFactoryReference bfr3;
BeanFactoryReference bfr4;
bfr = facLoc.useBeanFactory("a.qualified.name.of.some.sort");
fac = bfr.getFactory();
bfr2 = facLoc.useBeanFactory("another.qualified.name");
fac = bfr2.getFactory();
// verify that the same instance is returned
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("beans1.bean1"));
tb.setName("was beans1.bean1");
bfr3 = facLoc.useBeanFactory("another.qualified.name");
fac = bfr3.getFactory();
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("was beans1.bean1"));
bfr4 = facLoc.useBeanFactory("a.qualified.name.which.is.an.alias");
fac = bfr4.getFactory();
tb = (TestBean) fac.getBean("beans1.bean1");
assertTrue(tb.getName().equals("was beans1.bean1"));
bfr4.release();
bfr3.release();
bfr2.release();
bfr.release();
}
}
class TestBean {
private String name;
private List<?> list;
private Object objRef;
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return Returns the list.
*/
public List<?> getList() {
return list;
}
/**
* @param list The list to set.
*/
public void setList(List<?> list) {
this.list = list;
}
/**
* @return Returns the object.
*/
public Object getObjRef() {
return objRef;
}
/**
* @param object The object to set.
*/
public void setObjRef(Object object) {
this.objRef = object;
}
}

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="resolver" class="org.springframework.beans.factory.annotation.CustomAutowireConfigurerTests$CustomResolver"/>
<bean id="number-one" class="java.lang.String">
<meta key="priority" value="1"/>
<constructor-arg value="#1!"/>
</bean>
<bean id="one" class="java.lang.String" autowire-candidate="false">
<meta key="priority" value="1"/>
<constructor-arg value="#1"/>
</bean>
<bean id="number1" class="java.lang.String">
<meta key="priority" value="1"/>
<constructor-arg value="#1"/>
</bean>
<bean id="number-two" class="java.lang.String">
<meta key="priority" value="2"/>
<constructor-arg value="#2"/>
</bean>
<bean id="testBean"
class="org.springframework.beans.factory.annotation.CustomAutowireConfigurerTests$TestBean"
autowire="constructor"/>
</beans>

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2002-2008 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.beans.factory.annotation;
import static org.junit.Assert.assertEquals;
import static test.util.TestResourceUtils.qualifiedResource;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.AutowireCandidateResolver;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;
/**
* Unit tests for {@link CustomAutowireConfigurer}.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Chris Beams
*/
public final class CustomAutowireConfigurerTests {
private static final Resource CONTEXT = qualifiedResource(CustomAutowireConfigurerTests.class, "context.xml");
@Test
public void testCustomResolver() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
BeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
reader.loadBeanDefinitions(CONTEXT);
CustomAutowireConfigurer cac = new CustomAutowireConfigurer();
CustomResolver customResolver = new CustomResolver();
bf.setAutowireCandidateResolver(customResolver);
cac.postProcessBeanFactory(bf);
TestBean testBean = (TestBean) bf.getBean("testBean");
assertEquals("#1!", testBean.getName());
}
public static class TestBean {
private String name;
public TestBean(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
public static class CustomResolver implements AutowireCandidateResolver {
public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
if (!bdHolder.getBeanDefinition().isAutowireCandidate()) {
return false;
}
if (!bdHolder.getBeanName().matches("[a-z-]+")) {
return false;
}
if (bdHolder.getBeanDefinition().getAttribute("priority").equals("1")) {
return true;
}
return false;
}
public Object getSuggestedValue(DependencyDescriptor descriptor) {
return null;
}
}
}

View File

@@ -0,0 +1,867 @@
/*
* 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.beans.factory.annotation;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import static org.junit.Assert.*;
import org.junit.Test;
import test.beans.ITestBean;
import test.beans.IndexedTestBean;
import test.beans.NestedTestBean;
import test.beans.TestBean;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AutowireCandidateQualifier;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.util.SerializationTestUtils;
/**
* Unit tests for {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor}
* processing the JSR-303 {@link javax.inject.Inject} annotation.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class InjectAnnotationBeanPostProcessorTests {
@Test
public void testIncompleteBeanDefinition() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("testBean", new GenericBeanDefinition());
try {
bf.getBean("testBean");
}
catch (BeanCreationException ex) {
assertTrue(ex.getRootCause() instanceof IllegalStateException);
}
}
@Test
public void testResourceInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(ResourceInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean());
assertSame(tb, bean.getTestBean2());
bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean());
assertSame(tb, bean.getTestBean2());
}
@Test
public void testExtendedResourceInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerResolvableDependency(BeanFactory.class, bf);
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean());
assertSame(tb, bean.getTestBean2());
assertSame(tb, bean.getTestBean3());
assertSame(tb, bean.getTestBean4());
assertSame(ntb, bean.getNestedTestBean());
assertSame(bf, bean.getBeanFactory());
bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean());
assertSame(tb, bean.getTestBean2());
assertSame(tb, bean.getTestBean3());
assertSame(tb, bean.getTestBean4());
assertSame(ntb, bean.getNestedTestBean());
assertSame(bf, bean.getBeanFactory());
}
@Test
public void testExtendedResourceInjectionWithOverriding() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerResolvableDependency(BeanFactory.class, bf);
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition annotatedBd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
TestBean tb2 = new TestBean();
annotatedBd.getPropertyValues().add("testBean2", tb2);
bf.registerBeanDefinition("annotatedBean", annotatedBd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean());
assertSame(tb2, bean.getTestBean2());
assertSame(tb, bean.getTestBean3());
assertSame(tb, bean.getTestBean4());
assertSame(ntb, bean.getNestedTestBean());
assertSame(bf, bean.getBeanFactory());
bf.destroySingletons();
}
@Test
public void testExtendedResourceInjectionWithAtRequired() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerResolvableDependency(BeanFactory.class, bf);
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
RootBeanDefinition bd = new RootBeanDefinition(TypedExtendedResourceInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean());
assertSame(tb, bean.getTestBean2());
assertSame(tb, bean.getTestBean3());
assertSame(tb, bean.getTestBean4());
assertSame(ntb, bean.getNestedTestBean());
assertSame(bf, bean.getBeanFactory());
}
@Test
public void testConstructorResourceInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerResolvableDependency(BeanFactory.class, bf);
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(ConstructorResourceInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
NestedTestBean ntb = new NestedTestBean();
bf.registerSingleton("nestedTestBean", ntb);
ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean());
assertSame(tb, bean.getTestBean2());
assertSame(tb, bean.getTestBean3());
assertSame(tb, bean.getTestBean4());
assertSame(ntb, bean.getNestedTestBean());
assertSame(bf, bean.getBeanFactory());
bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean());
assertSame(tb, bean.getTestBean2());
assertSame(tb, bean.getTestBean3());
assertSame(tb, bean.getTestBean4());
assertSame(ntb, bean.getNestedTestBean());
assertSame(bf, bean.getBeanFactory());
}
@Test
public void testConstructorResourceInjectionWithMultipleCandidatesAsCollection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(
ConstructorsCollectionResourceInjectionBean.class));
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
NestedTestBean ntb1 = new NestedTestBean();
bf.registerSingleton("nestedTestBean1", ntb1);
NestedTestBean ntb2 = new NestedTestBean();
bf.registerSingleton("nestedTestBean2", ntb2);
ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean");
assertNull(bean.getTestBean3());
assertSame(tb, bean.getTestBean4());
assertEquals(2, bean.getNestedTestBeans().size());
assertSame(ntb1, bean.getNestedTestBeans().get(0));
assertSame(ntb2, bean.getNestedTestBeans().get(1));
bf.destroySingletons();
}
@Test
public void testConstructorResourceInjectionWithMultipleCandidatesAndFallback() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ConstructorsResourceInjectionBean.class));
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean3());
assertNull(bean.getTestBean4());
bf.destroySingletons();
}
@Test
public void testConstructorInjectionWithMap() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(MapConstructorInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb1 = new TestBean();
TestBean tb2 = new TestBean();
bf.registerSingleton("testBean1", tb1);
bf.registerSingleton("testBean2", tb1);
MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertEquals(2, bean.getTestBeanMap().size());
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1"));
assertTrue(bean.getTestBeanMap().keySet().contains("testBean2"));
assertTrue(bean.getTestBeanMap().values().contains(tb1));
assertTrue(bean.getTestBeanMap().values().contains(tb2));
bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertEquals(2, bean.getTestBeanMap().size());
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1"));
assertTrue(bean.getTestBeanMap().keySet().contains("testBean2"));
assertTrue(bean.getTestBeanMap().values().contains(tb1));
assertTrue(bean.getTestBeanMap().values().contains(tb2));
}
@Test
public void testFieldInjectionWithMap() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(MapFieldInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb1 = new TestBean();
TestBean tb2 = new TestBean();
bf.registerSingleton("testBean1", tb1);
bf.registerSingleton("testBean2", tb1);
MapFieldInjectionBean bean = (MapFieldInjectionBean) bf.getBean("annotatedBean");
assertEquals(2, bean.getTestBeanMap().size());
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1"));
assertTrue(bean.getTestBeanMap().keySet().contains("testBean2"));
assertTrue(bean.getTestBeanMap().values().contains(tb1));
assertTrue(bean.getTestBeanMap().values().contains(tb2));
bean = (MapFieldInjectionBean) bf.getBean("annotatedBean");
assertEquals(2, bean.getTestBeanMap().size());
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1"));
assertTrue(bean.getTestBeanMap().keySet().contains("testBean2"));
assertTrue(bean.getTestBeanMap().values().contains(tb1));
assertTrue(bean.getTestBeanMap().values().contains(tb2));
}
@Test
public void testMethodInjectionWithMap() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition bd = new RootBeanDefinition(MapMethodInjectionBean.class);
bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
assertEquals(1, bean.getTestBeanMap().size());
assertTrue(bean.getTestBeanMap().keySet().contains("testBean"));
assertTrue(bean.getTestBeanMap().values().contains(tb));
assertSame(tb, bean.getTestBean());
bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
assertEquals(1, bean.getTestBeanMap().size());
assertTrue(bean.getTestBeanMap().keySet().contains("testBean"));
assertTrue(bean.getTestBeanMap().values().contains(tb));
assertSame(tb, bean.getTestBean());
}
@Test
public void testMethodInjectionWithMapAndMultipleMatches() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
try {
bf.getBean("annotatedBean");
fail("should have failed, more than one bean of type");
}
catch (BeanCreationException e) {
// expected
}
bf.destroySingletons();
}
@Test
public void testMethodInjectionWithMapAndMultipleMatchesButOnlyOneAutowireCandidate() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
RootBeanDefinition rbd2 = new RootBeanDefinition(TestBean.class);
rbd2.setAutowireCandidate(false);
bf.registerBeanDefinition("testBean2", rbd2);
MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
TestBean tb = (TestBean) bf.getBean("testBean1");
assertEquals(1, bean.getTestBeanMap().size());
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1"));
assertTrue(bean.getTestBeanMap().values().contains(tb));
assertSame(tb, bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryQualifierInjectionBean.class));
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "testBean"));
bf.registerBeanDefinition("testBean", bd);
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
ObjectFactoryQualifierInjectionBean bean = (ObjectFactoryQualifierInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactoryQualifierInjection() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryQualifierInjectionBean.class));
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "testBean"));
bf.registerBeanDefinition("testBean", bd);
ObjectFactoryQualifierInjectionBean bean = (ObjectFactoryQualifierInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
@Test
public void testObjectFactorySerialization() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryInjectionBean.class));
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
bf.setSerializationId("test");
ObjectFactoryInjectionBean bean = (ObjectFactoryInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean());
bean = (ObjectFactoryInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean());
bf.destroySingletons();
}
/**
* Verifies that a dependency on a {@link org.springframework.beans.factory.FactoryBean} can be autowired via
* {@link org.springframework.beans.factory.annotation.Autowired @Inject}, specifically addressing the JIRA issue
* raised in <a
* href="http://opensource.atlassian.com/projects/spring/browse/SPR-4040"
* target="_blank">SPR-4040</a>.
*/
@Test
public void testBeanAutowiredWithFactoryBean() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition("factoryBeanDependentBean", new RootBeanDefinition(FactoryBeanDependentBean.class));
bf.registerSingleton("stringFactoryBean", new StringFactoryBean());
final StringFactoryBean factoryBean = (StringFactoryBean) bf.getBean("&stringFactoryBean");
final FactoryBeanDependentBean bean = (FactoryBeanDependentBean) bf.getBean("factoryBeanDependentBean");
assertNotNull("The singleton StringFactoryBean should have been registered.", factoryBean);
assertNotNull("The factoryBeanDependentBean should have been registered.", bean);
assertEquals("The FactoryBeanDependentBean should have been autowired 'by type' with the StringFactoryBean.",
factoryBean, bean.getFactoryBean());
bf.destroySingletons();
}
public static class ResourceInjectionBean {
@Inject
private TestBean testBean;
private TestBean testBean2;
@Inject
public void setTestBean2(TestBean testBean2) {
if (this.testBean2 != null) {
throw new IllegalStateException("Already called");
}
this.testBean2 = testBean2;
}
public TestBean getTestBean() {
return this.testBean;
}
public TestBean getTestBean2() {
return this.testBean2;
}
}
public static class ExtendedResourceInjectionBean<T> extends ResourceInjectionBean {
@Inject
protected ITestBean testBean3;
private T nestedTestBean;
private ITestBean testBean4;
private BeanFactory beanFactory;
public ExtendedResourceInjectionBean() {
}
@Inject @Required
public void setTestBean2(TestBean testBean2) {
super.setTestBean2(testBean2);
}
@Inject
private void inject(ITestBean testBean4, T nestedTestBean) {
this.testBean4 = testBean4;
this.nestedTestBean = nestedTestBean;
}
@Inject
protected void initBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public ITestBean getTestBean3() {
return this.testBean3;
}
public ITestBean getTestBean4() {
return this.testBean4;
}
public T getNestedTestBean() {
return this.nestedTestBean;
}
public BeanFactory getBeanFactory() {
return this.beanFactory;
}
}
public static class TypedExtendedResourceInjectionBean extends ExtendedResourceInjectionBean<NestedTestBean> {
}
public static class OptionalResourceInjectionBean extends ResourceInjectionBean {
@Inject
protected ITestBean testBean3;
private IndexedTestBean indexedTestBean;
private NestedTestBean[] nestedTestBeans;
@Inject
public NestedTestBean[] nestedTestBeansField;
private ITestBean testBean4;
@Inject
public void setTestBean2(TestBean testBean2) {
super.setTestBean2(testBean2);
}
@Inject
private void inject(ITestBean testBean4, NestedTestBean[] nestedTestBeans, IndexedTestBean indexedTestBean) {
this.testBean4 = testBean4;
this.indexedTestBean = indexedTestBean;
this.nestedTestBeans = nestedTestBeans;
}
public ITestBean getTestBean3() {
return this.testBean3;
}
public ITestBean getTestBean4() {
return this.testBean4;
}
public IndexedTestBean getIndexedTestBean() {
return this.indexedTestBean;
}
public NestedTestBean[] getNestedTestBeans() {
return this.nestedTestBeans;
}
}
public static class OptionalCollectionResourceInjectionBean extends ResourceInjectionBean {
@Inject
protected ITestBean testBean3;
private IndexedTestBean indexedTestBean;
private List<NestedTestBean> nestedTestBeans;
public List<NestedTestBean> nestedTestBeansSetter;
@Inject
public List<NestedTestBean> nestedTestBeansField;
private ITestBean testBean4;
@Inject
public void setTestBean2(TestBean testBean2) {
super.setTestBean2(testBean2);
}
@Inject
private void inject(ITestBean testBean4, List<NestedTestBean> nestedTestBeans, IndexedTestBean indexedTestBean) {
this.testBean4 = testBean4;
this.indexedTestBean = indexedTestBean;
this.nestedTestBeans = nestedTestBeans;
}
@Inject
public void setNestedTestBeans(List<NestedTestBean> nestedTestBeans) {
this.nestedTestBeansSetter = nestedTestBeans;
}
public ITestBean getTestBean3() {
return this.testBean3;
}
public ITestBean getTestBean4() {
return this.testBean4;
}
public IndexedTestBean getIndexedTestBean() {
return this.indexedTestBean;
}
public List<NestedTestBean> getNestedTestBeans() {
return this.nestedTestBeans;
}
}
public static class ConstructorResourceInjectionBean extends ResourceInjectionBean {
@Inject
protected ITestBean testBean3;
private ITestBean testBean4;
private NestedTestBean nestedTestBean;
private ConfigurableListableBeanFactory beanFactory;
public ConstructorResourceInjectionBean() {
throw new UnsupportedOperationException();
}
public ConstructorResourceInjectionBean(ITestBean testBean3) {
throw new UnsupportedOperationException();
}
@Inject
public ConstructorResourceInjectionBean(ITestBean testBean4, NestedTestBean nestedTestBean,
ConfigurableListableBeanFactory beanFactory) {
this.testBean4 = testBean4;
this.nestedTestBean = nestedTestBean;
this.beanFactory = beanFactory;
}
public ConstructorResourceInjectionBean(NestedTestBean nestedTestBean) {
throw new UnsupportedOperationException();
}
public ConstructorResourceInjectionBean(ITestBean testBean3, ITestBean testBean4, NestedTestBean nestedTestBean) {
throw new UnsupportedOperationException();
}
@Inject
public void setTestBean2(TestBean testBean2) {
super.setTestBean2(testBean2);
}
public ITestBean getTestBean3() {
return this.testBean3;
}
public ITestBean getTestBean4() {
return this.testBean4;
}
public NestedTestBean getNestedTestBean() {
return this.nestedTestBean;
}
public ConfigurableListableBeanFactory getBeanFactory() {
return this.beanFactory;
}
}
public static class ConstructorsResourceInjectionBean {
protected ITestBean testBean3;
private ITestBean testBean4;
private NestedTestBean[] nestedTestBeans;
public ConstructorsResourceInjectionBean() {
}
@Inject
public ConstructorsResourceInjectionBean(ITestBean testBean3) {
this.testBean3 = testBean3;
}
public ConstructorsResourceInjectionBean(ITestBean testBean4, NestedTestBean[] nestedTestBeans) {
this.testBean4 = testBean4;
this.nestedTestBeans = nestedTestBeans;
}
public ConstructorsResourceInjectionBean(NestedTestBean nestedTestBean) {
throw new UnsupportedOperationException();
}
public ConstructorsResourceInjectionBean(ITestBean testBean3, ITestBean testBean4, NestedTestBean nestedTestBean) {
throw new UnsupportedOperationException();
}
public ITestBean getTestBean3() {
return this.testBean3;
}
public ITestBean getTestBean4() {
return this.testBean4;
}
public NestedTestBean[] getNestedTestBeans() {
return this.nestedTestBeans;
}
}
public static class ConstructorsCollectionResourceInjectionBean {
protected ITestBean testBean3;
private ITestBean testBean4;
private List<NestedTestBean> nestedTestBeans;
public ConstructorsCollectionResourceInjectionBean() {
}
public ConstructorsCollectionResourceInjectionBean(ITestBean testBean3) {
this.testBean3 = testBean3;
}
@Inject
public ConstructorsCollectionResourceInjectionBean(ITestBean testBean4, List<NestedTestBean> nestedTestBeans) {
this.testBean4 = testBean4;
this.nestedTestBeans = nestedTestBeans;
}
public ConstructorsCollectionResourceInjectionBean(NestedTestBean nestedTestBean) {
throw new UnsupportedOperationException();
}
public ConstructorsCollectionResourceInjectionBean(ITestBean testBean3, ITestBean testBean4,
NestedTestBean nestedTestBean) {
throw new UnsupportedOperationException();
}
public ITestBean getTestBean3() {
return this.testBean3;
}
public ITestBean getTestBean4() {
return this.testBean4;
}
public List<NestedTestBean> getNestedTestBeans() {
return this.nestedTestBeans;
}
}
public static class MapConstructorInjectionBean {
private Map<String, TestBean> testBeanMap;
@Inject
public MapConstructorInjectionBean(Map<String, TestBean> testBeanMap) {
this.testBeanMap = testBeanMap;
}
public Map<String, TestBean> getTestBeanMap() {
return this.testBeanMap;
}
}
public static class MapFieldInjectionBean {
@Inject
private Map<String, TestBean> testBeanMap;
public Map<String, TestBean> getTestBeanMap() {
return this.testBeanMap;
}
}
public static class MapMethodInjectionBean {
private TestBean testBean;
private Map<String, TestBean> testBeanMap;
@Inject
public void setTestBeanMap(TestBean testBean, Map<String, TestBean> testBeanMap) {
this.testBean = testBean;
this.testBeanMap = testBeanMap;
}
public TestBean getTestBean() {
return this.testBean;
}
public Map<String, TestBean> getTestBeanMap() {
return this.testBeanMap;
}
}
public static class ObjectFactoryInjectionBean implements Serializable {
@Inject
private Provider<TestBean> testBeanFactory;
public TestBean getTestBean() {
return this.testBeanFactory.get();
}
}
public static class ObjectFactoryQualifierInjectionBean {
@Inject
@Named("testBean")
private Provider<?> testBeanFactory;
public TestBean getTestBean() {
return (TestBean) this.testBeanFactory.get();
}
}
/**
* Bean with a dependency on a {@link org.springframework.beans.factory.FactoryBean}.
*/
private static class FactoryBeanDependentBean {
@Inject
private FactoryBean<?> factoryBean;
public final FactoryBean<?> getFactoryBean() {
return this.factoryBean;
}
}
public static class StringFactoryBean implements FactoryBean<String> {
public String getObject() throws Exception {
return "";
}
public Class<String> getObjectType() {
return String.class;
}
public boolean isSingleton() {
return true;
}
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2002-2008 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.beans.factory.config;
import static org.junit.Assert.*;
import org.apache.commons.logging.Log;
import org.junit.Test;
/**
* Unit tests for {@link CommonsLogFactoryBean}.
*
* @author Rick Evans
* @author Chris Beams
*/
public final class CommonsLogFactoryBeanTests {
@Test
public void testIsSingleton() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
assertTrue(factory.isSingleton());
}
@Test
public void testGetObjectTypeDefaultsToPlainResourceInterfaceifLookupResourceIsNotSupplied() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
assertEquals(Log.class, factory.getObjectType());
}
@Test(expected=IllegalArgumentException.class)
public void testWhenLogNameIsMissing() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
factory.afterPropertiesSet();
}
@Test
public void testSunnyDayPath() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
factory.setLogName("The Tin Drum");
factory.afterPropertiesSet();
Object object = factory.getObject();
assertNotNull("As per FactoryBean contract, the return value of getObject() cannot be null.", object);
assertTrue("Obviously not getting a Log back", Log.class.isAssignableFrom(object.getClass()));
}
}

View File

@@ -0,0 +1,197 @@
/*
* 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.beans.factory.config;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import static org.junit.Assert.*;
import org.junit.Test;
import test.beans.TestBean;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.propertyeditors.CustomDateEditor;
/**
* Unit tests for {@link CustomEditorConfigurer}.
*
* @author Juergen Hoeller
* @author Chris Beams
* @since 31.07.2004
*/
public final class CustomEditorConfigurerTests {
@Test
public void testCustomEditorConfigurerWithPropertyEditorRegistrar() throws ParseException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CustomEditorConfigurer cec = new CustomEditorConfigurer();
final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
cec.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] {
new PropertyEditorRegistrar() {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
}
}});
cec.postProcessBeanFactory(bf);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("date", "2.12.1975");
bf.registerBeanDefinition("tb1", new RootBeanDefinition(TestBean.class, pvs));
pvs = new MutablePropertyValues();
pvs.add("someMap[myKey]", new TypedStringValue("2.12.1975", Date.class));
bf.registerBeanDefinition("tb2", new RootBeanDefinition(TestBean.class, pvs));
TestBean tb1 = (TestBean) bf.getBean("tb1");
assertEquals(df.parse("2.12.1975"), tb1.getDate());
TestBean tb2 = (TestBean) bf.getBean("tb2");
assertEquals(df.parse("2.12.1975"), tb2.getSomeMap().get("myKey"));
}
@Test
public void testCustomEditorConfigurerWithEditorInstance() throws ParseException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CustomEditorConfigurer cec = new CustomEditorConfigurer();
Map<String, PropertyEditor> editors = new HashMap<String, PropertyEditor>();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
editors.put(Date.class.getName(), new CustomDateEditor(df, true));
cec.setCustomEditors(editors);
cec.postProcessBeanFactory(bf);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("date", "2.12.1975");
bf.registerBeanDefinition("tb1", new RootBeanDefinition(TestBean.class, pvs));
pvs = new MutablePropertyValues();
pvs.add("someMap[myKey]", new TypedStringValue("2.12.1975", Date.class));
bf.registerBeanDefinition("tb2", new RootBeanDefinition(TestBean.class, pvs));
TestBean tb1 = (TestBean) bf.getBean("tb1");
assertEquals(df.parse("2.12.1975"), tb1.getDate());
TestBean tb2 = (TestBean) bf.getBean("tb2");
assertEquals(df.parse("2.12.1975"), tb2.getSomeMap().get("myKey"));
}
@Test
public void testCustomEditorConfigurerWithEditorClassName() throws ParseException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CustomEditorConfigurer cec = new CustomEditorConfigurer();
Map<String, String> editors = new HashMap<String, String>();
editors.put(Date.class.getName(), MyDateEditor.class.getName());
cec.setCustomEditors(editors);
cec.postProcessBeanFactory(bf);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("date", "2.12.1975");
bf.registerBeanDefinition("tb", new RootBeanDefinition(TestBean.class, pvs));
TestBean tb = (TestBean) bf.getBean("tb");
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
assertEquals(df.parse("2.12.1975"), tb.getDate());
}
@Test
public void testCustomEditorConfigurerWithEditorAsClass() throws ParseException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CustomEditorConfigurer cec = new CustomEditorConfigurer();
Map<String, Class> editors = new HashMap<String, Class>();
editors.put(Date.class.getName(), MyDateEditor.class);
cec.setCustomEditors(editors);
cec.postProcessBeanFactory(bf);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("date", "2.12.1975");
bf.registerBeanDefinition("tb", new RootBeanDefinition(TestBean.class, pvs));
TestBean tb = (TestBean) bf.getBean("tb");
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
assertEquals(df.parse("2.12.1975"), tb.getDate());
}
@Test
public void testCustomEditorConfigurerWithRequiredTypeArray() throws ParseException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CustomEditorConfigurer cec = new CustomEditorConfigurer();
Map<String, String> editors = new HashMap<String, String>();
editors.put("java.lang.String[]", MyTestEditor.class.getName());
cec.setCustomEditors(editors);
cec.postProcessBeanFactory(bf);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("stringArray", "xxx");
bf.registerBeanDefinition("tb", new RootBeanDefinition(TestBean.class, pvs));
TestBean tb = (TestBean) bf.getBean("tb");
assertTrue(tb.getStringArray() != null && tb.getStringArray().length == 1);
assertEquals("test", tb.getStringArray()[0]);
}
@Test
public void testCustomEditorConfigurerWithUnresolvableEditor() throws ParseException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CustomEditorConfigurer cec = new CustomEditorConfigurer();
Map<String, String> editors = new HashMap<String, String>();
editors.put(Date.class.getName(), "MyNonExistingEditor");
editors.put("MyNonExistingType", "MyNonExistingEditor");
cec.setCustomEditors(editors);
try {
cec.postProcessBeanFactory(bf);
fail("Should have thrown FatalBeanException");
}
catch (FatalBeanException ex) {
assertTrue(ex.getCause() instanceof ClassNotFoundException);
}
}
@Test
public void testCustomEditorConfigurerWithIgnoredUnresolvableEditor() throws ParseException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CustomEditorConfigurer cec = new CustomEditorConfigurer();
Map<String, String> editors = new HashMap<String, String>();
editors.put(Date.class.getName(), "MyNonExistingEditor");
editors.put("MyNonExistingType", "MyNonExistingEditor");
cec.setCustomEditors(editors);
cec.setIgnoreUnresolvableEditors(true);
cec.postProcessBeanFactory(bf);
}
public static class MyDateEditor extends CustomDateEditor {
public MyDateEditor() {
super(DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN), true);
}
}
public static class MyTestEditor extends PropertyEditorSupport {
public void setAsText(String text) {
setValue(new String[] {"test"});
}
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright 2002-2008 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.beans.factory.config;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
/**
* Unit tests for {@link CustomScopeConfigurer}.
*
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public final class CustomScopeConfigurerTests {
private static final String FOO_SCOPE = "fooScope";
private ConfigurableListableBeanFactory factory;
@Before
public void setUp() {
factory = new DefaultListableBeanFactory();
}
@Test
public void testWithNoScopes() throws Exception {
Scope scope = createMock(Scope.class);
replay(scope);
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.postProcessBeanFactory(factory);
verify(scope);
}
@Test
public void testSunnyDayWithBonaFideScopeInstance() throws Exception {
Scope scope = createMock(Scope.class);
replay(scope);
factory.registerScope(FOO_SCOPE, scope);
Map<String, Object> scopes = new HashMap<String, Object>();
scopes.put(FOO_SCOPE, scope);
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
verify(scope);
}
@Test
public void testSunnyDayWithBonaFideScopeClass() throws Exception {
Map<String, Object> scopes = new HashMap<String, Object>();
scopes.put(FOO_SCOPE, NoOpScope.class);
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
assertTrue(factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope);
}
@Test
public void testSunnyDayWithBonaFideScopeClassname() throws Exception {
Map<String, Object> scopes = new HashMap<String, Object>();
scopes.put(FOO_SCOPE, NoOpScope.class.getName());
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
assertTrue(factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope);
}
@Test(expected=IllegalArgumentException.class)
public void testWhereScopeMapHasNullScopeValueInEntrySet() throws Exception {
Map<String, Object> scopes = new HashMap<String, Object>();
scopes.put(FOO_SCOPE, null);
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
}
@Test(expected=IllegalArgumentException.class)
public void testWhereScopeMapHasNonScopeInstanceInEntrySet() throws Exception {
Map<String, Object> scopes = new HashMap<String, Object>();
scopes.put(FOO_SCOPE, this); // <-- not a valid value...
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
}
@SuppressWarnings("unchecked")
@Test(expected=ClassCastException.class)
public void testWhereScopeMapHasNonStringTypedScopeNameInKeySet() throws Exception {
Map scopes = new HashMap();
scopes.put(this, new NoOpScope()); // <-- not a valid value (the key)...
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2002-2010 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.beans.factory.config;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
/**
* @author Arjen Poutsma
*/
public class DeprecatedBeanWarnerTests {
private DefaultListableBeanFactory beanFactory;
private String beanName;
private BeanDefinition beanDefinition;
private DeprecatedBeanWarner warner;
@Test
public void postProcess() {
beanFactory = new DefaultListableBeanFactory();
BeanDefinition def = BeanDefinitionBuilder
.genericBeanDefinition(MyDeprecatedBean.class)
.getBeanDefinition();
String beanName = "deprecated";
beanFactory.registerBeanDefinition(beanName, def);
warner = new MyDeprecatedBeanWarner();
warner.postProcessBeanFactory(beanFactory);
assertEquals(beanName, this.beanName);
assertEquals(def, this.beanDefinition);
}
private class MyDeprecatedBeanWarner extends DeprecatedBeanWarner {
@Override
protected void logDeprecatedBean(String beanName, BeanDefinition beanDefinition) {
DeprecatedBeanWarnerTests.this.beanName = beanName;
DeprecatedBeanWarnerTests.this.beanDefinition = beanDefinition;
}
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="testBean" class="test.beans.TestBean">
<property name="someIntegerArray">
<list>
<bean name="java.sql.Connection.TRANSACTION_SERIALIZABLE" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>
<bean name="java.sql.Connection.TRANSACTION_SERIALIZABLE" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>
</list>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,142 @@
/*
* Copyright 2002-2008 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.beans.factory.config;
import static org.junit.Assert.assertEquals;
import static test.util.TestResourceUtils.qualifiedResource;
import java.sql.Connection;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;
import test.beans.TestBean;
/**
* Unit tests for {@link FieldRetrievingFactoryBean}.
*
* @author Juergen Hoeller
* @author Chris Beams
* @since 31.07.2004
*/
public final class FieldRetrievingFactoryBeanTests {
private static final Resource CONTEXT =
qualifiedResource(FieldRetrievingFactoryBeanTests.class, "context.xml");
@Test
public void testStaticField() throws Exception {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setStaticField("java.sql.Connection.TRANSACTION_SERIALIZABLE");
fr.afterPropertiesSet();
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject());
}
@Test
public void testStaticFieldWithWhitespace() throws Exception {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setStaticField(" java.sql.Connection.TRANSACTION_SERIALIZABLE ");
fr.afterPropertiesSet();
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject());
}
@Test
public void testStaticFieldViaClassAndFieldName() throws Exception {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setTargetClass(Connection.class);
fr.setTargetField("TRANSACTION_SERIALIZABLE");
fr.afterPropertiesSet();
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject());
}
@Test
public void testNonStaticField() throws Exception {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
PublicFieldHolder target = new PublicFieldHolder();
fr.setTargetObject(target);
fr.setTargetField("publicField");
fr.afterPropertiesSet();
assertEquals(target.publicField, fr.getObject());
}
@Test
public void testNothingButBeanName() throws Exception {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setBeanName("java.sql.Connection.TRANSACTION_SERIALIZABLE");
fr.afterPropertiesSet();
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject());
}
@Test
public void testJustTargetField() throws Exception {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setTargetField("TRANSACTION_SERIALIZABLE");
try {
fr.afterPropertiesSet();
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testJustTargetClass() throws Exception {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setTargetClass(Connection.class);
try {
fr.afterPropertiesSet();
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testJustTargetObject() throws Exception {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setTargetObject(new PublicFieldHolder());
try {
fr.afterPropertiesSet();
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testWithConstantOnClassWithPackageLevelVisibility() throws Exception {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setBeanName("test.beans.PackageLevelVisibleBean.CONSTANT");
fr.afterPropertiesSet();
assertEquals("Wuby", fr.getObject());
}
@Test
public void testBeanNameSyntaxWithBeanFactory() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(CONTEXT);
TestBean testBean = (TestBean) bf.getBean("testBean");
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), testBean.getSomeIntegerArray()[0]);
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), testBean.getSomeIntegerArray()[1]);
}
private static class PublicFieldHolder {
public String publicField = "test";
}
}

View File

@@ -0,0 +1,399 @@
/*
* Copyright 2002-2008 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.beans.factory.config;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.beans.support.ArgumentConvertingMethodInvoker;
import org.springframework.util.MethodInvoker;
/**
* Unit tests for {@link MethodInvokingFactoryBean}.
*
* @author Colin Sampaleanu
* @author Juergen Hoeller
* @author Chris Beams
* @since 21.11.2003
*/
public final class MethodInvokingFactoryBeanTests {
@Test
public void testParameterValidation() throws Exception {
String validationError = "improper validation of input properties";
// assert that only static OR non static are set, but not both or none
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (IllegalArgumentException ex) {
// expected
}
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(this);
mcfb.setTargetMethod("whatever");
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (NoSuchMethodException ex) {
// expected
}
// bogus static method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("some.bogus.Method.name");
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (NoSuchMethodException ex) {
// expected
}
// bogus static method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("method1");
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (IllegalArgumentException ex) {
// expected
}
// missing method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(this);
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (IllegalArgumentException ex) {
// expected
}
// bogus method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(this);
mcfb.setTargetMethod("bogus");
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (NoSuchMethodException ex) {
// expected
}
// static method
TestClass1._staticField1 = 0;
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("staticMethod1");
mcfb.afterPropertiesSet();
// non-static method
TestClass1 tc1 = new TestClass1();
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(tc1);
mcfb.setTargetMethod("method1");
mcfb.afterPropertiesSet();
}
@Test
public void testGetObjectType() throws Exception {
TestClass1 tc1 = new TestClass1();
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(tc1);
mcfb.setTargetMethod("method1");
mcfb.afterPropertiesSet();
assertTrue(int.class.equals(mcfb.getObjectType()));
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("voidRetvalMethod");
mcfb.afterPropertiesSet();
Class<?> objType = mcfb.getObjectType();
assertTrue(objType.equals(void.class));
// verify that we can call a method with args that are subtypes of the
// target method arg types
TestClass1._staticField1 = 0;
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new Object[] {new ArrayList<Object>(), new ArrayList<Object>(), "hello"});
mcfb.afterPropertiesSet();
mcfb.getObjectType();
// fail on improper argument types at afterPropertiesSet
mcfb = new MethodInvokingFactoryBean();
mcfb.registerCustomEditor(String.class, new StringTrimmerEditor(false));
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new Object[] {"1", new Object()});
try {
mcfb.afterPropertiesSet();
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException ex) {
// expected
}
}
@Test
public void testGetObject() throws Exception {
// singleton, non-static
TestClass1 tc1 = new TestClass1();
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(tc1);
mcfb.setTargetMethod("method1");
mcfb.afterPropertiesSet();
Integer i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue());
i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue());
// non-singleton, non-static
tc1 = new TestClass1();
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(tc1);
mcfb.setTargetMethod("method1");
mcfb.setSingleton(false);
mcfb.afterPropertiesSet();
i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue());
i = (Integer) mcfb.getObject();
assertEquals(2, i.intValue());
// singleton, static
TestClass1._staticField1 = 0;
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("staticMethod1");
mcfb.afterPropertiesSet();
i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue());
i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue());
// non-singleton, static
TestClass1._staticField1 = 0;
mcfb = new MethodInvokingFactoryBean();
mcfb.setStaticMethod("org.springframework.beans.factory.config.MethodInvokingFactoryBeanTests$TestClass1.staticMethod1");
mcfb.setSingleton(false);
mcfb.afterPropertiesSet();
i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue());
i = (Integer) mcfb.getObject();
assertEquals(2, i.intValue());
// void return value
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("voidRetvalMethod");
mcfb.afterPropertiesSet();
assertNull(mcfb.getObject());
// now see if we can match methods with arguments that have supertype arguments
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new Object[] {new ArrayList<Object>(), new ArrayList<Object>(), "hello"});
// should pass
mcfb.afterPropertiesSet();
}
@Test
public void testArgumentConversion() throws Exception {
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new Object[] {new ArrayList<Object>(), new ArrayList<Object>(), "hello", "bogus"});
try {
mcfb.afterPropertiesSet();
fail("Matched method with wrong number of args");
}
catch (NoSuchMethodException ex) {
// expected
}
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new Object[] {new Integer(1), new Object()});
try {
mcfb.afterPropertiesSet();
mcfb.getObject();
fail("Should have failed on getObject with mismatched argument types");
}
catch (NoSuchMethodException ex) {
// expected
}
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new Object[] {new ArrayList<Object>(), new ArrayList<Object>(), "hello", "bogus"});
mcfb.afterPropertiesSet();
assertEquals("hello", mcfb.getObject());
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new Object[] {new ArrayList<Object>(), new ArrayList<Object>(), new Object()});
try {
mcfb.afterPropertiesSet();
fail("Matched method when shouldn't have matched");
}
catch (NoSuchMethodException ex) {
// expected
}
}
@Test
public void testInvokeWithNullArgument() throws Exception {
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("nullArgument");
methodInvoker.setArguments(new Object[] {null});
methodInvoker.prepare();
methodInvoker.invoke();
}
@Test
public void testInvokeWithIntArgument() throws Exception {
ArgumentConvertingMethodInvoker methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArgument");
methodInvoker.setArguments(new Object[] {new Integer(5)});
methodInvoker.prepare();
methodInvoker.invoke();
methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArgument");
methodInvoker.setArguments(new Object[] {"5"});
methodInvoker.prepare();
methodInvoker.invoke();
}
@Test
public void testInvokeWithIntArguments() throws Exception {
ArgumentConvertingMethodInvoker methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new Object[] {new Integer[] {new Integer(5), new Integer(10)}});
methodInvoker.prepare();
methodInvoker.invoke();
methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new Object[] {new String[] {"5", "10"}});
methodInvoker.prepare();
methodInvoker.invoke();
methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new Integer[] {new Integer(5), new Integer(10)});
methodInvoker.prepare();
methodInvoker.invoke();
methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new String[] {"5", "10"});
methodInvoker.prepare();
methodInvoker.invoke();
methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new Object[] {new Integer(5), new Integer(10)});
methodInvoker.prepare();
methodInvoker.invoke();
methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new Object[] {"5", "10"});
methodInvoker.prepare();
methodInvoker.invoke();
}
public static class TestClass1 {
public static int _staticField1;
public int _field1 = 0;
public int method1() {
return ++_field1;
}
public static int staticMethod1() {
return ++TestClass1._staticField1;
}
public static void voidRetvalMethod() {
}
public static void nullArgument(Object arg) {
}
public static void intArgument(int arg) {
}
public static void intArguments(int[] arg) {
}
public static String supertypes(Collection<?> c, Integer i) {
return i.toString();
}
public static String supertypes(Collection<?> c, List<?> l, String s) {
return s;
}
public static String supertypes2(Collection<?> c, List<?> l, Integer i) {
return i.toString();
}
public static String supertypes2(Collection<?> c, List<?> l, String s, Integer i) {
return s;
}
public static String supertypes2(Collection<?> c, List<?> l, String s, String s2) {
return s;
}
}
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright 2002-2010 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.beans.factory.config;
@Deprecated
public class MyDeprecatedBean {
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="prototypeTarget" class="java.util.Date" scope="prototype"/>
<bean id="prototypeFactory" class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
<property name="targetBeanName" value="prototypeTarget"/>
</bean>
<bean id="factoryTestBean" class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBeanTests$FactoryTestBean">
<property name="objectFactory" ref="prototypeFactory"/>
</bean>
<bean id="prototypeProvider" class="org.springframework.beans.factory.config.ProviderCreatingFactoryBean">
<property name="targetBeanName" value="prototypeTarget"/>
</bean>
<bean id="providerTestBean" class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBeanTests$ProviderTestBean">
<property name="provider" ref="prototypeProvider"/>
</bean>
</beans>

View File

@@ -0,0 +1,188 @@
/*
* Copyright 2002-2010 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.beans.factory.config;
import java.util.Date;
import javax.inject.Provider;
import static org.easymock.EasyMock.*;
import org.junit.After;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import static test.util.TestResourceUtils.*;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.util.SerializationTestUtils;
/**
* @author Colin Sampaleanu
* @author Juergen Hoeller
* @author Rick Evans
* @author Chris Beams
*/
public class ObjectFactoryCreatingFactoryBeanTests {
private static final Resource CONTEXT =
qualifiedResource(ObjectFactoryCreatingFactoryBeanTests.class, "context.xml");
private XmlBeanFactory beanFactory;
@Before
public void setUp() {
this.beanFactory = new XmlBeanFactory(CONTEXT);
this.beanFactory.setSerializationId("test");
}
@After
public void tearDown() {
this.beanFactory.setSerializationId(null);
}
@Test
public void testFactoryOperation() throws Exception {
FactoryTestBean testBean = beanFactory.getBean("factoryTestBean", FactoryTestBean.class);
ObjectFactory<?> objectFactory = testBean.getObjectFactory();
Date date1 = (Date) objectFactory.getObject();
Date date2 = (Date) objectFactory.getObject();
assertTrue(date1 != date2);
}
@Test
public void testFactorySerialization() throws Exception {
FactoryTestBean testBean = beanFactory.getBean("factoryTestBean", FactoryTestBean.class);
ObjectFactory<?> objectFactory = testBean.getObjectFactory();
objectFactory = (ObjectFactory) SerializationTestUtils.serializeAndDeserialize(objectFactory);
Date date1 = (Date) objectFactory.getObject();
Date date2 = (Date) objectFactory.getObject();
assertTrue(date1 != date2);
}
@Test
public void testProviderOperation() throws Exception {
ProviderTestBean testBean = beanFactory.getBean("providerTestBean", ProviderTestBean.class);
Provider<?> provider = testBean.getProvider();
Date date1 = (Date) provider.get();
Date date2 = (Date) provider.get();
assertTrue(date1 != date2);
}
@Test
public void testProviderSerialization() throws Exception {
ProviderTestBean testBean = beanFactory.getBean("providerTestBean", ProviderTestBean.class);
Provider<?> provider = testBean.getProvider();
provider = (Provider) SerializationTestUtils.serializeAndDeserialize(provider);
Date date1 = (Date) provider.get();
Date date2 = (Date) provider.get();
assertTrue(date1 != date2);
}
@Test
public void testDoesNotComplainWhenTargetBeanNameRefersToSingleton() throws Exception {
final String targetBeanName = "singleton";
final String expectedSingleton = "Alicia Keys";
BeanFactory beanFactory = createMock(BeanFactory.class);
expect(beanFactory.getBean(targetBeanName)).andReturn(expectedSingleton);
replay(beanFactory);
ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean();
factory.setTargetBeanName(targetBeanName);
factory.setBeanFactory(beanFactory);
factory.afterPropertiesSet();
ObjectFactory<?> objectFactory = (ObjectFactory<?>) factory.getObject();
Object actualSingleton = objectFactory.getObject();
assertSame(expectedSingleton, actualSingleton);
verify(beanFactory);
}
@Test
public void testWhenTargetBeanNameIsNull() throws Exception {
try {
new ObjectFactoryCreatingFactoryBean().afterPropertiesSet();
fail("Must have thrown an IllegalArgumentException; 'targetBeanName' property not set.");
}
catch (IllegalArgumentException expected) {}
}
@Test
public void testWhenTargetBeanNameIsEmptyString() throws Exception {
try {
ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean();
factory.setTargetBeanName("");
factory.afterPropertiesSet();
fail("Must have thrown an IllegalArgumentException; 'targetBeanName' property set to (invalid) empty string.");
}
catch (IllegalArgumentException expected) {}
}
@Test
public void testWhenTargetBeanNameIsWhitespacedString() throws Exception {
try {
ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean();
factory.setTargetBeanName(" \t");
factory.afterPropertiesSet();
fail("Must have thrown an IllegalArgumentException; 'targetBeanName' property set to (invalid) only-whitespace string.");
}
catch (IllegalArgumentException expected) {}
}
@Test
public void testEnsureOFBFBReportsThatItActuallyCreatesObjectFactoryInstances() throws Exception {
assertEquals("Must be reporting that it creates ObjectFactory instances (as per class contract).",
ObjectFactory.class, new ObjectFactoryCreatingFactoryBean().getObjectType());
}
public static class FactoryTestBean {
private ObjectFactory<?> objectFactory;
public ObjectFactory<?> getObjectFactory() {
return objectFactory;
}
public void setObjectFactory(ObjectFactory<?> objectFactory) {
this.objectFactory = objectFactory;
}
}
public static class ProviderTestBean {
private Provider<?> provider;
public Provider<?> getProvider() {
return provider;
}
public void setProvider(Provider<?> provider) {
this.provider = provider;
}
}
}

View File

@@ -0,0 +1,2 @@
tb.array[0].age=99
tb.list[1].name=test

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties version="1.0">
<entry key="tb.array[0].age">99</entry>
<entry key="tb.list[1].name">test</entry>
</properties>

View File

@@ -0,0 +1,145 @@
/*
* Copyright 2002-2008 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.beans.factory.config;
import static org.junit.Assert.*;
import static test.util.TestResourceUtils.qualifiedResource;
import java.util.Properties;
import org.junit.Test;
import org.springframework.core.io.Resource;
/**
* Unit tests for {@link PropertiesFactoryBean}.
*
* @author Juergen Hoeller
* @author Chris Beams
* @since 01.11.2003
*/
public final class PropertiesFactoryBeanTests {
private static final Class<?> CLASS = PropertiesFactoryBeanTests.class;
private static final Resource TEST_PROPS = qualifiedResource(CLASS, "test.properties");
private static final Resource TEST_PROPS_XML = qualifiedResource(CLASS, "test.properties.xml");
@Test
public void testWithPropertiesFile() throws Exception {
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setLocation(TEST_PROPS);
pfb.afterPropertiesSet();
Properties props = (Properties) pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age"));
}
@Test
public void testWithPropertiesXmlFile() throws Exception {
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setLocation(TEST_PROPS_XML);
pfb.afterPropertiesSet();
Properties props = (Properties) pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age"));
}
@Test
public void testWithLocalProperties() throws Exception {
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
Properties localProps = new Properties();
localProps.setProperty("key2", "value2");
pfb.setProperties(localProps);
pfb.afterPropertiesSet();
Properties props = (Properties) pfb.getObject();
assertEquals("value2", props.getProperty("key2"));
}
@Test
public void testWithPropertiesFileAndLocalProperties() throws Exception {
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setLocation(TEST_PROPS);
Properties localProps = new Properties();
localProps.setProperty("key2", "value2");
localProps.setProperty("tb.array[0].age", "0");
pfb.setProperties(localProps);
pfb.afterPropertiesSet();
Properties props = (Properties) pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age"));
assertEquals("value2", props.getProperty("key2"));
}
@Test
public void testWithPropertiesFileAndMultipleLocalProperties() throws Exception {
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setLocation(TEST_PROPS);
Properties props1 = new Properties();
props1.setProperty("key2", "value2");
props1.setProperty("tb.array[0].age", "0");
Properties props2 = new Properties();
props2.setProperty("spring", "framework");
props2.setProperty("Don", "Mattingly");
Properties props3 = new Properties();
props3.setProperty("spider", "man");
props3.setProperty("bat", "man");
pfb.setPropertiesArray(new Properties[] {props1, props2, props3});
pfb.afterPropertiesSet();
Properties props = (Properties) pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age"));
assertEquals("value2", props.getProperty("key2"));
assertEquals("framework", props.getProperty("spring"));
assertEquals("Mattingly", props.getProperty("Don"));
assertEquals("man", props.getProperty("spider"));
assertEquals("man", props.getProperty("bat"));
}
@Test
public void testWithPropertiesFileAndLocalPropertiesAndLocalOverride() throws Exception {
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setLocation(TEST_PROPS);
Properties localProps = new Properties();
localProps.setProperty("key2", "value2");
localProps.setProperty("tb.array[0].age", "0");
pfb.setProperties(localProps);
pfb.setLocalOverride(true);
pfb.afterPropertiesSet();
Properties props = (Properties) pfb.getObject();
assertEquals("0", props.getProperty("tb.array[0].age"));
assertEquals("value2", props.getProperty("key2"));
}
@Test
public void testWithPrototype() throws Exception {
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setSingleton(false);
pfb.setLocation(TEST_PROPS);
Properties localProps = new Properties();
localProps.setProperty("key2", "value2");
pfb.setProperties(localProps);
pfb.afterPropertiesSet();
Properties props = (Properties) pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age"));
assertEquals("value2", props.getProperty("key2"));
Properties newProps = (Properties) pfb.getObject();
assertTrue(props != newProps);
assertEquals("99", newProps.getProperty("tb.array[0].age"));
assertEquals("value2", newProps.getProperty("key2"));
}
}

View File

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="tb" class="test.beans.TestBean" scope="prototype">
<property name="age"><value>10</value></property>
<property name="spouse">
<bean class="test.beans.TestBean">
<property name="age"><value>11</value></property>
</bean>
</property>
</bean>
<bean id="otb" class="test.beans.TestBean">
<property name="age"><value>98</value></property>
<property name="spouse">
<bean class="test.beans.TestBean">
<property name="age"><value>99</value></property>
</bean>
</property>
</bean>
<bean id="propertyPath1" class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetObject">
<bean class="test.beans.TestBean">
<property name="age"><value>12</value></property>
</bean>
</property>
<property name="propertyPath"><value>age</value></property>
</bean>
<bean id="propertyPath2" class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetBeanName"><value>tb</value></property>
<property name="propertyPath"><value>spouse.age</value></property>
</bean>
<bean id="tb.age" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
<bean id="otb.spouse" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
<bean id="tb.spouse" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
<bean id="tb.spouse.spouse" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
<bean id="propertyPath3" class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetBeanName"><value>tb</value></property>
<property name="propertyPath"><value>spouse</value></property>
<property name="resultType"><value>test.beans.TestBean</value></property>
</bean>
<bean id="tbWithInner" class="test.beans.TestBean">
<property name="age" value="10"/>
<property name="spouse">
<bean name="otb.spouse" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
</property>
<property name="friends">
<bean name="otb.spouse" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2002-2008 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.beans.factory.config;
import static org.junit.Assert.*;
import static test.util.TestResourceUtils.qualifiedResource;
import org.junit.Test;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import test.beans.ITestBean;
import test.beans.TestBean;
/**
* Unit tests for {@link PropertyPathFactoryBean}.
*
* @author Juergen Hoeller
* @author Chris Beams
* @since 04.10.2004
*/
public class PropertyPathFactoryBeanTests {
private static final Resource CONTEXT = qualifiedResource(PropertyPathFactoryBeanTests.class, "context.xml");
@Test
public void testPropertyPathFactoryBeanWithSingletonResult() {
XmlBeanFactory xbf = new XmlBeanFactory(CONTEXT);
assertEquals(new Integer(12), xbf.getBean("propertyPath1"));
assertEquals(new Integer(11), xbf.getBean("propertyPath2"));
assertEquals(new Integer(10), xbf.getBean("tb.age"));
assertEquals(ITestBean.class, xbf.getType("otb.spouse"));
Object result1 = xbf.getBean("otb.spouse");
Object result2 = xbf.getBean("otb.spouse");
assertTrue(result1 instanceof TestBean);
assertTrue(result1 == result2);
assertEquals(99, ((TestBean) result1).getAge());
}
@Test
public void testPropertyPathFactoryBeanWithPrototypeResult() {
XmlBeanFactory xbf = new XmlBeanFactory(CONTEXT);
assertNull(xbf.getType("tb.spouse"));
assertEquals(TestBean.class, xbf.getType("propertyPath3"));
Object result1 = xbf.getBean("tb.spouse");
Object result2 = xbf.getBean("propertyPath3");
Object result3 = xbf.getBean("propertyPath3");
assertTrue(result1 instanceof TestBean);
assertTrue(result2 instanceof TestBean);
assertTrue(result3 instanceof TestBean);
assertEquals(11, ((TestBean) result1).getAge());
assertEquals(11, ((TestBean) result2).getAge());
assertEquals(11, ((TestBean) result3).getAge());
assertTrue(result1 != result2);
assertTrue(result1 != result3);
assertTrue(result2 != result3);
}
@Test
public void testPropertyPathFactoryBeanWithNullResult() {
XmlBeanFactory xbf = new XmlBeanFactory(CONTEXT);
assertNull(xbf.getType("tb.spouse.spouse"));
assertNull(xbf.getBean("tb.spouse.spouse"));
}
@Test
public void testPropertyPathFactoryBeanAsInnerBean() {
XmlBeanFactory xbf = new XmlBeanFactory(CONTEXT);
TestBean spouse = (TestBean) xbf.getBean("otb.spouse");
TestBean tbWithInner = (TestBean) xbf.getBean("tbWithInner");
assertSame(spouse, tbWithInner.getSpouse());
assertTrue(!tbWithInner.getFriends().isEmpty());
assertSame(spouse, tbWithInner.getFriends().iterator().next());
}
}

View File

@@ -0,0 +1,298 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.config;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.registerWithGeneratedName;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import test.beans.TestBean;
/**
* Unit tests for {@link PropertyPlaceholderConfigurer}.
*
* @see PropertySourcesPlaceholderConfigurerTests
* @see PropertyResourceConfigurerTests
* @author Chris Beams
*/
public class PropertyPlaceholderConfigurerTests {
private static final String P1 = "p1";
private static final String P1_LOCAL_PROPS_VAL = "p1LocalPropsVal";
private static final String P1_SYSTEM_PROPS_VAL = "p1SystemPropsVal";
private static final String P1_SYSTEM_ENV_VAL = "p1SystemEnvVal";
private DefaultListableBeanFactory bf;
private PropertyPlaceholderConfigurer ppc;
private Properties ppcProperties;
private AbstractBeanDefinition p1BeanDef;
@Before
public void setUp() {
p1BeanDef = rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "${"+P1+"}")
.getBeanDefinition();
bf = new DefaultListableBeanFactory();
ppcProperties = new Properties();
ppcProperties.setProperty(P1, P1_LOCAL_PROPS_VAL);
System.setProperty(P1, P1_SYSTEM_PROPS_VAL);
getModifiableSystemEnvironment().put(P1, P1_SYSTEM_ENV_VAL);
ppc = new PropertyPlaceholderConfigurer();
ppc.setProperties(ppcProperties);
}
@After
public void tearDown() {
System.clearProperty(P1);
getModifiableSystemEnvironment().remove(P1);
}
@Test
public void localPropertiesViaResource() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("testBean",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${my.name}")
.getBeanDefinition());
PropertyPlaceholderConfigurer pc = new PropertyPlaceholderConfigurer();
Resource resource = new ClassPathResource("PropertyPlaceholderConfigurerTests.properties", this.getClass());
pc.setLocation(resource);
pc.postProcessBeanFactory(bf);
}
@Test
public void resolveFromSystemProperties() {
getModifiableSystemEnvironment().put("otherKey", "systemValue");
p1BeanDef = rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "${"+P1+"}")
.addPropertyValue("sex", "${otherKey}")
.getBeanDefinition();
registerWithGeneratedName(p1BeanDef, bf);
ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL));
assertThat(bean.getSex(), equalTo("systemValue"));
getModifiableSystemEnvironment().remove("otherKey");
}
@Test
public void resolveFromLocalProperties() {
tearDown(); // eliminate entries from system props/environment
registerWithGeneratedName(p1BeanDef, bf);
ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL));
}
@Test
public void setSystemPropertiesMode_defaultIsFallback() {
registerWithGeneratedName(p1BeanDef, bf);
ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL));
}
@Test
public void setSystemSystemPropertiesMode_toOverride_andResolveFromSystemProperties() {
registerWithGeneratedName(p1BeanDef, bf);
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_SYSTEM_PROPS_VAL));
}
@Test
public void setSystemSystemPropertiesMode_toOverride_andResolveFromSystemEnvironment() {
registerWithGeneratedName(p1BeanDef, bf);
System.clearProperty(P1); // will now fall all the way back to system environment
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_SYSTEM_ENV_VAL));
}
@Test
public void setSystemSystemPropertiesMode_toOverride_andSetSearchSystemEnvironment_toFalse() {
registerWithGeneratedName(p1BeanDef, bf);
System.clearProperty(P1); // will now fall all the way back to system environment
ppc.setSearchSystemEnvironment(false);
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); // has to resort to local props
}
/**
* Creates a scenario in which two PPCs are configured, each with different
* settings regarding resolving properties from the environment.
*/
@Test
public void twoPlacholderConfigurers_withConflictingSettings() {
String P2 = "p2";
String P2_LOCAL_PROPS_VAL = "p2LocalPropsVal";
String P2_SYSTEM_PROPS_VAL = "p2SystemPropsVal";
String P2_SYSTEM_ENV_VAL = "p2SystemEnvVal";
AbstractBeanDefinition p2BeanDef = rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "${"+P1+"}")
.addPropertyValue("country", "${"+P2+"}")
.getBeanDefinition();
bf.registerBeanDefinition("p1Bean", p1BeanDef);
bf.registerBeanDefinition("p2Bean", p2BeanDef);
ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.postProcessBeanFactory(bf);
System.setProperty(P2, P2_SYSTEM_PROPS_VAL);
getModifiableSystemEnvironment().put(P2, P2_SYSTEM_ENV_VAL);
Properties ppc2Properties = new Properties();
ppc2Properties.put(P2, P2_LOCAL_PROPS_VAL);
PropertyPlaceholderConfigurer ppc2 = new PropertyPlaceholderConfigurer();
ppc2.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
ppc2.setProperties(ppc2Properties);
ppc2Properties = new Properties();
ppc2Properties.setProperty(P2, P2_LOCAL_PROPS_VAL);
ppc2.postProcessBeanFactory(bf);
TestBean p1Bean = bf.getBean("p1Bean", TestBean.class);
assertThat(p1Bean.getName(), equalTo(P1_LOCAL_PROPS_VAL));
TestBean p2Bean = bf.getBean("p2Bean", TestBean.class);
assertThat(p2Bean.getName(), equalTo(P1_LOCAL_PROPS_VAL));
assertThat(p2Bean.getCountry(), equalTo(P2_SYSTEM_PROPS_VAL));
System.clearProperty(P2);
getModifiableSystemEnvironment().remove(P2);
}
@Test
public void customPlaceholderPrefixAndSuffix() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setPlaceholderPrefix("@<");
ppc.setPlaceholderSuffix(">");
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("testBean",
rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "@<key1>")
.addPropertyValue("sex", "${key2}")
.getBeanDefinition());
System.setProperty("key1", "systemKey1Value");
System.setProperty("key2", "systemKey2Value");
ppc.postProcessBeanFactory(bf);
System.clearProperty("key1");
System.clearProperty("key2");
assertThat(bf.getBean(TestBean.class).getName(), is("systemKey1Value"));
assertThat(bf.getBean(TestBean.class).getSex(), is("${key2}"));
}
@Test
public void nullValueIsPreserved() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setNullValue("customNull");
getModifiableSystemEnvironment().put("my.name", "customNull");
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("testBean", rootBeanDefinition(TestBean.class)
.addPropertyValue("name", "${my.name}")
.getBeanDefinition());
ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), nullValue());
getModifiableSystemEnvironment().remove("my.name");
}
@SuppressWarnings("unchecked")
private static Map<String, String> getModifiableSystemEnvironment() {
// for os x / linux
Class<?>[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for (Class<?> cl : classes) {
if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
try {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
if (obj != null && obj.getClass().getName().equals("java.lang.ProcessEnvironment$StringEnvironment")) {
return (Map<String, String>) obj;
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
// for windows
Class<?> processEnvironmentClass;
try {
processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Object obj = theCaseInsensitiveEnvironmentField.get(null);
return (Map<String, String>) obj;
} catch (NoSuchFieldException e) {
// do nothing
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Object obj = theEnvironmentField.get(null);
return (Map<String, String>) obj;
} catch (NoSuchFieldException e) {
// do nothing
} catch (Exception e) {
throw new RuntimeException(e);
}
throw new IllegalStateException();
}
}

View File

@@ -0,0 +1,2 @@
tb.array[0].age=99
tb.list[1].name=test

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties version="1.0">
<entry key="tb.array[0].age">99</entry>
<entry key="tb.list[1].name">test</entry>
</properties>

View File

@@ -0,0 +1,811 @@
/*
* Copyright 2002-2010 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.beans.factory.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
import static test.util.TestResourceUtils.qualifiedResource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.prefs.Preferences;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ChildBeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.support.ManagedSet;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.io.Resource;
import test.beans.IndexedTestBean;
import test.beans.TestBean;
/**
* Unit tests for various {@link PropertyResourceConfigurer} implementations including:
* {@link PropertyPlaceholderConfigurer}, {@link PropertyOverrideConfigurer} and
* {@link PreferencesPlaceholderConfigurer}.
*
* @see PropertyPlaceholderConfigurerTests
* @since 02.10.2003
* @author Juergen Hoeller
* @author Chris Beams
*/
public final class PropertyResourceConfigurerTests {
private static final Class<?> CLASS = PropertyResourceConfigurerTests.class;
private static final Resource TEST_PROPS = qualifiedResource(CLASS, "test.properties");
private static final Resource XTEST_PROPS = qualifiedResource(CLASS, "xtest.properties"); // does not exist
private static final Resource TEST_PROPS_XML = qualifiedResource(CLASS, "test.properties.xml");
private DefaultListableBeanFactory factory;
@Before
public void setUp() {
factory = new DefaultListableBeanFactory();
}
@Test
public void testPropertyOverrideConfigurer() {
BeanDefinition def1 = BeanDefinitionBuilder
.genericBeanDefinition(TestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("tb1", def1);
BeanDefinition def2 = BeanDefinitionBuilder
.genericBeanDefinition(TestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("tb2", def2);
PropertyOverrideConfigurer poc1;
PropertyOverrideConfigurer poc2;
{
poc1 = new PropertyOverrideConfigurer();
Properties props = new Properties();
props.setProperty("tb1.age", "99");
props.setProperty("tb2.name", "test");
poc1.setProperties(props);
}
{
poc2 = new PropertyOverrideConfigurer();
Properties props = new Properties();
props.setProperty("tb2.age", "99");
props.setProperty("tb2.name", "test2");
poc2.setProperties(props);
}
// emulate what happens when BFPPs are added to an application context: It's LIFO-based
poc2.postProcessBeanFactory(factory);
poc1.postProcessBeanFactory(factory);
TestBean tb1 = (TestBean) factory.getBean("tb1");
TestBean tb2 = (TestBean) factory.getBean("tb2");
assertEquals(99, tb1.getAge());
assertEquals(99, tb2.getAge());
assertEquals(null, tb1.getName());
assertEquals("test", tb2.getName());
}
@Test
public void testPropertyOverrideConfigurerWithNestedProperty() {
BeanDefinition def = BeanDefinitionBuilder
.genericBeanDefinition(IndexedTestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("tb", def);
PropertyOverrideConfigurer poc;
poc = new PropertyOverrideConfigurer();
Properties props = new Properties();
props.setProperty("tb.array[0].age", "99");
props.setProperty("tb.list[1].name", "test");
poc.setProperties(props);
poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals(99, tb.getArray()[0].getAge());
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
public void testPropertyOverrideConfigurerWithNestedPropertyAndDotInBeanName() {
BeanDefinition def = BeanDefinitionBuilder
.genericBeanDefinition(IndexedTestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("my.tb", def);
PropertyOverrideConfigurer poc;
poc = new PropertyOverrideConfigurer();
Properties props = new Properties();
props.setProperty("my.tb_array[0].age", "99");
props.setProperty("my.tb_list[1].name", "test");
poc.setProperties(props);
poc.setBeanNameSeparator("_");
poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("my.tb");
assertEquals(99, tb.getArray()[0].getAge());
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
public void testPropertyOverrideConfigurerWithNestedMapPropertyAndDotInMapKey() {
BeanDefinition def = BeanDefinitionBuilder
.genericBeanDefinition(IndexedTestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("tb", def);
PropertyOverrideConfigurer poc;
poc = new PropertyOverrideConfigurer();
Properties props = new Properties();
props.setProperty("tb.map[key1]", "99");
props.setProperty("tb.map[key2.ext]", "test");
poc.setProperties(props);
poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals("99", tb.getMap().get("key1"));
assertEquals("test", tb.getMap().get("key2.ext"));
}
@Test
public void testPropertyOverrideConfigurerWithHeldProperties() {
BeanDefinition def = BeanDefinitionBuilder
.genericBeanDefinition(PropertiesHolder.class)
.getBeanDefinition();
factory.registerBeanDefinition("tb", def);
PropertyOverrideConfigurer poc;
poc = new PropertyOverrideConfigurer();
Properties props = new Properties();
props.setProperty("tb.heldProperties[mail.smtp.auth]", "true");
poc.setProperties(props);
poc.postProcessBeanFactory(factory);
PropertiesHolder tb = (PropertiesHolder) factory.getBean("tb");
assertEquals("true", tb.getHeldProperties().getProperty("mail.smtp.auth"));
}
static class PropertiesHolder {
private Properties props = new Properties();
public Properties getHeldProperties() {
return props;
}
public void setHeldProperties(Properties props) {
this.props = props;
}
}
@Test
public void testPropertyOverrideConfigurerWithPropertiesFile() {
BeanDefinition def = BeanDefinitionBuilder
.genericBeanDefinition(IndexedTestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("tb", def);
PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer();
poc.setLocation(TEST_PROPS);
poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals(99, tb.getArray()[0].getAge());
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
public void testPropertyOverrideConfigurerWithInvalidPropertiesFile() {
BeanDefinition def = BeanDefinitionBuilder
.genericBeanDefinition(IndexedTestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("tb", def);
PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer();
poc.setLocations(new Resource[] { TEST_PROPS, XTEST_PROPS });
poc.setIgnoreResourceNotFound(true);
poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals(99, tb.getArray()[0].getAge());
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
public void testPropertyOverrideConfigurerWithPropertiesXmlFile() {
BeanDefinition def = BeanDefinitionBuilder
.genericBeanDefinition(IndexedTestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("tb", def);
PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer();
poc.setLocation(TEST_PROPS_XML);
poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals(99, tb.getArray()[0].getAge());
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
public void testPropertyOverrideConfigurerWithConvertProperties() {
BeanDefinition def = BeanDefinitionBuilder
.genericBeanDefinition(IndexedTestBean.class)
.getBeanDefinition();
factory.registerBeanDefinition("tb", def);
ConvertingOverrideConfigurer bfpp = new ConvertingOverrideConfigurer();
Properties props = new Properties();
props.setProperty("tb.array[0].name", "99");
props.setProperty("tb.list[1].name", "test");
bfpp.setProperties(props);
bfpp.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals("X99", tb.getArray()[0].getName());
assertEquals("Xtest", ((TestBean) tb.getList().get(1)).getName());
}
@Test
public void testPropertyOverrideConfigurerWithInvalidKey() {
factory.registerBeanDefinition("tb1", genericBeanDefinition(TestBean.class).getBeanDefinition());
factory.registerBeanDefinition("tb2", genericBeanDefinition(TestBean.class).getBeanDefinition());
{
PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer();
poc.setIgnoreInvalidKeys(true);
Properties props = new Properties();
props.setProperty("argh", "hgra");
props.setProperty("tb2.name", "test");
props.setProperty("tb2.nam", "test");
props.setProperty("tb3.name", "test");
poc.setProperties(props);
poc.postProcessBeanFactory(factory);
assertEquals("test", factory.getBean("tb2", TestBean.class).getName());
}
{
PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer();
Properties props = new Properties();
props.setProperty("argh", "hgra");
props.setProperty("tb2.age", "99");
props.setProperty("tb2.name", "test2");
poc.setProperties(props);
poc.setOrder(0); // won't actually do anything since we're not processing through an app ctx
try {
poc.postProcessBeanFactory(factory);
}
catch (BeanInitializationException ex) {
// prove that the processor chokes on the invalid key
assertTrue(ex.getMessage().toLowerCase().contains("argh"));
}
}
}
@Test
public void testPropertyOverrideConfigurerWithIgnoreInvalidKeys() {
factory.registerBeanDefinition("tb1", genericBeanDefinition(TestBean.class).getBeanDefinition());
factory.registerBeanDefinition("tb2", genericBeanDefinition(TestBean.class).getBeanDefinition());
{
PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer();
Properties props = new Properties();
props.setProperty("tb2.age", "99");
props.setProperty("tb2.name", "test2");
poc.setProperties(props);
poc.setOrder(0); // won't actually do anything since we're not processing through an app ctx
poc.postProcessBeanFactory(factory);
}
{
PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer();
poc.setIgnoreInvalidKeys(true);
Properties props = new Properties();
props.setProperty("argh", "hgra");
props.setProperty("tb1.age", "99");
props.setProperty("tb2.name", "test");
poc.setProperties(props);
poc.postProcessBeanFactory(factory);
}
TestBean tb1 = (TestBean) factory.getBean("tb1");
TestBean tb2 = (TestBean) factory.getBean("tb2");
assertEquals(99, tb1.getAge());
assertEquals(99, tb2.getAge());
assertEquals(null, tb1.getName());
assertEquals("test", tb2.getName());
}
@Test
public void testPropertyPlaceholderConfigurer() {
doTestPropertyPlaceholderConfigurer(false);
}
@Test
public void testPropertyPlaceholderConfigurerWithParentChildSeparation() {
doTestPropertyPlaceholderConfigurer(true);
}
private void doTestPropertyPlaceholderConfigurer(boolean parentChildSeparation) {
Map singletonMap = Collections.singletonMap("myKey", "myValue");
if (parentChildSeparation) {
MutablePropertyValues pvs1 = new MutablePropertyValues();
pvs1.add("age", "${age}");
MutablePropertyValues pvs2 = new MutablePropertyValues();
pvs2.add("name", "name${var}${var}${");
pvs2.add("spouse", new RuntimeBeanReference("${ref}"));
pvs2.add("someMap", singletonMap);
RootBeanDefinition parent = new RootBeanDefinition(TestBean.class, pvs1);
ChildBeanDefinition bd = new ChildBeanDefinition("${parent}", pvs2);
factory.registerBeanDefinition("parent1", parent);
factory.registerBeanDefinition("tb1", bd);
}
else {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("age", "${age}");
pvs.add("name", "name${var}${var}${");
pvs.add("spouse", new RuntimeBeanReference("${ref}"));
pvs.add("someMap", singletonMap);
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class, pvs);
factory.registerBeanDefinition("tb1", bd);
}
ConstructorArgumentValues cas = new ConstructorArgumentValues();
cas.addIndexedArgumentValue(1, "${age}");
cas.addGenericArgumentValue("${var}name${age}");
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("stringArray", new String[] {"${os.name}", "${age}"});
List<Object> friends = new ManagedList<Object>();
friends.add("na${age}me");
friends.add(new RuntimeBeanReference("${ref}"));
pvs.add("friends", friends);
Set<Object> someSet = new ManagedSet<Object>();
someSet.add("na${age}me");
someSet.add(new RuntimeBeanReference("${ref}"));
someSet.add(new TypedStringValue("${age}", Integer.class));
pvs.add("someSet", someSet);
Map<Object, Object> someMap = new ManagedMap<Object, Object>();
someMap.put(new TypedStringValue("key${age}"), new TypedStringValue("${age}"));
someMap.put(new TypedStringValue("key${age}ref"), new RuntimeBeanReference("${ref}"));
someMap.put("key1", new RuntimeBeanReference("${ref}"));
someMap.put("key2", "${age}name");
MutablePropertyValues innerPvs = new MutablePropertyValues();
innerPvs.add("touchy", "${os.name}");
someMap.put("key3", new RootBeanDefinition(TestBean.class, innerPvs));
MutablePropertyValues innerPvs2 = new MutablePropertyValues(innerPvs);
someMap.put("${key4}", new BeanDefinitionHolder(new ChildBeanDefinition("tb1", innerPvs2), "child"));
pvs.add("someMap", someMap);
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class, cas, pvs);
factory.registerBeanDefinition("tb2", bd);
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("age", "98");
props.setProperty("var", "${m}var");
props.setProperty("ref", "tb2");
props.setProperty("m", "my");
props.setProperty("key4", "mykey4");
props.setProperty("parent", "parent1");
ppc.setProperties(props);
ppc.postProcessBeanFactory(factory);
TestBean tb1 = (TestBean) factory.getBean("tb1");
TestBean tb2 = (TestBean) factory.getBean("tb2");
assertEquals(98, tb1.getAge());
assertEquals(98, tb2.getAge());
assertEquals("namemyvarmyvar${", tb1.getName());
assertEquals("myvarname98", tb2.getName());
assertEquals(tb2, tb1.getSpouse());
assertEquals(1, tb1.getSomeMap().size());
assertEquals("myValue", tb1.getSomeMap().get("myKey"));
assertEquals(2, tb2.getStringArray().length);
assertEquals(System.getProperty("os.name"), tb2.getStringArray()[0]);
assertEquals("98", tb2.getStringArray()[1]);
assertEquals(2, tb2.getFriends().size());
assertEquals("na98me", tb2.getFriends().iterator().next());
assertEquals(tb2, tb2.getFriends().toArray()[1]);
assertEquals(3, tb2.getSomeSet().size());
assertTrue(tb2.getSomeSet().contains("na98me"));
assertTrue(tb2.getSomeSet().contains(tb2));
assertTrue(tb2.getSomeSet().contains(new Integer(98)));
assertEquals(6, tb2.getSomeMap().size());
assertEquals("98", tb2.getSomeMap().get("key98"));
assertEquals(tb2, tb2.getSomeMap().get("key98ref"));
assertEquals(tb2, tb2.getSomeMap().get("key1"));
assertEquals("98name", tb2.getSomeMap().get("key2"));
TestBean inner1 = (TestBean) tb2.getSomeMap().get("key3");
TestBean inner2 = (TestBean) tb2.getSomeMap().get("mykey4");
assertEquals(0, inner1.getAge());
assertEquals(null, inner1.getName());
assertEquals(System.getProperty("os.name"), inner1.getTouchy());
assertEquals(98, inner2.getAge());
assertEquals("namemyvarmyvar${", inner2.getName());
assertEquals(System.getProperty("os.name"), inner2.getTouchy());
}
@Test
public void testPropertyPlaceholderConfigurerWithSystemPropertyFallback() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("touchy", "${os.name}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals(System.getProperty("os.name"), tb.getTouchy());
}
@Test
public void testPropertyPlaceholderConfigurerWithSystemPropertyNotUsed() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("touchy", "${os.name}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("os.name", "myos");
ppc.setProperties(props);
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myos", tb.getTouchy());
}
@Test
public void testPropertyPlaceholderConfigurerWithOverridingSystemProperty() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("touchy", "${os.name}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.put("os.name", "myos");
ppc.setProperties(props);
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals(System.getProperty("os.name"), tb.getTouchy());
}
@Test
public void testPropertyPlaceholderConfigurerWithUnresolvableSystemProperty() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("touchy", "${user.dir}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_NEVER);
try {
ppc.postProcessBeanFactory(factory);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getMessage().contains("user.dir"));
}
}
@Test
public void testPropertyPlaceholderConfigurerWithUnresolvablePlaceholder() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${ref}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
try {
ppc.postProcessBeanFactory(factory);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getMessage().contains("ref"));
}
}
@Test
public void testPropertyPlaceholderConfigurerWithIgnoreUnresolvablePlaceholder() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${ref}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("${ref}", tb.getName());
}
@Test
public void testPropertyPlaceholderConfigurerWithEmptyStringAsNull() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setNullValue("");
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertNull(tb.getName());
}
@Test
public void testPropertyPlaceholderConfigurerWithEmptyStringInPlaceholderAsNull() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${ref}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setNullValue("");
Properties props = new Properties();
props.put("ref", "");
ppc.setProperties(props);
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertNull(tb.getName());
}
@Test
public void testPropertyPlaceholderConfigurerWithNestedPlaceholderInKey() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${my${key}key}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.put("key", "new");
props.put("mynewkey", "myname");
ppc.setProperties(props);
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myname", tb.getName());
}
@Test
public void testPropertyPlaceholderConfigurerWithPlaceholderInAlias() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class).getBeanDefinition());
factory.registerAlias("tb", "${alias}");
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.put("alias", "tb2");
ppc.setProperties(props);
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
TestBean tb2 = (TestBean) factory.getBean("tb2");
assertSame(tb, tb2);
}
@Test
public void testPropertyPlaceholderConfigurerWithSelfReferencingPlaceholderInAlias() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class).getBeanDefinition());
factory.registerAlias("tb", "${alias}");
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.put("alias", "tb");
ppc.setProperties(props);
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals(0, factory.getAliases("tb").length);
}
@Test
public void testPropertyPlaceholderConfigurerWithCircularReference() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("age", "${age}")
.addPropertyValue("name", "name${var}")
.getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("age", "99");
props.setProperty("var", "${m}");
props.setProperty("m", "${var}");
ppc.setProperties(props);
try {
ppc.postProcessBeanFactory(factory);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
}
@Test
public void testPropertyPlaceholderConfigurerWithDefaultProperties() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("touchy", "${test}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.put("test", "mytest");
ppc.setProperties(props);
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("mytest", tb.getTouchy());
}
@Test
public void testPropertyPlaceholderConfigurerWithInlineDefault() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("touchy", "${test:mytest}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("mytest", tb.getTouchy());
}
@Test
public void testPropertyPlaceholderConfigurerWithAliases() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("touchy", "${test}").getBeanDefinition());
factory.registerAlias("tb", "${myAlias}");
factory.registerAlias("${myTarget}", "alias2");
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.put("test", "mytest");
props.put("myAlias", "alias");
props.put("myTarget", "tb");
ppc.setProperties(props);
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("mytest", tb.getTouchy());
tb = (TestBean) factory.getBean("alias");
assertEquals("mytest", tb.getTouchy());
tb = (TestBean) factory.getBean("alias2");
assertEquals("mytest", tb.getTouchy());
}
@Test
public void testPreferencesPlaceholderConfigurer() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${myName}")
.addPropertyValue("age", "${myAge}")
.addPropertyValue("touchy", "${myTouchy}")
.getBeanDefinition());
PreferencesPlaceholderConfigurer ppc = new PreferencesPlaceholderConfigurer();
Properties props = new Properties();
props.put("myAge", "99");
ppc.setProperties(props);
Preferences.systemRoot().put("myName", "myNameValue");
Preferences.systemRoot().put("myTouchy", "myTouchyValue");
Preferences.userRoot().put("myTouchy", "myOtherTouchyValue");
ppc.afterPropertiesSet();
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myNameValue", tb.getName());
assertEquals(99, tb.getAge());
assertEquals("myOtherTouchyValue", tb.getTouchy());
Preferences.userRoot().remove("myTouchy");
Preferences.systemRoot().remove("myTouchy");
Preferences.systemRoot().remove("myName");
}
@Test
public void testPreferencesPlaceholderConfigurerWithCustomTreePaths() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${myName}")
.addPropertyValue("age", "${myAge}")
.addPropertyValue("touchy", "${myTouchy}")
.getBeanDefinition());
PreferencesPlaceholderConfigurer ppc = new PreferencesPlaceholderConfigurer();
Properties props = new Properties();
props.put("myAge", "99");
ppc.setProperties(props);
ppc.setSystemTreePath("mySystemPath");
ppc.setUserTreePath("myUserPath");
Preferences.systemRoot().node("mySystemPath").put("myName", "myNameValue");
Preferences.systemRoot().node("mySystemPath").put("myTouchy", "myTouchyValue");
Preferences.userRoot().node("myUserPath").put("myTouchy", "myOtherTouchyValue");
ppc.afterPropertiesSet();
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myNameValue", tb.getName());
assertEquals(99, tb.getAge());
assertEquals("myOtherTouchyValue", tb.getTouchy());
Preferences.userRoot().node("myUserPath").remove("myTouchy");
Preferences.systemRoot().node("mySystemPath").remove("myTouchy");
Preferences.systemRoot().node("mySystemPath").remove("myName");
}
@Test
public void testPreferencesPlaceholderConfigurerWithPathInPlaceholder() {
factory.registerBeanDefinition("tb",
genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${mypath/myName}")
.addPropertyValue("age", "${myAge}")
.addPropertyValue("touchy", "${myotherpath/myTouchy}")
.getBeanDefinition());
PreferencesPlaceholderConfigurer ppc = new PreferencesPlaceholderConfigurer();
Properties props = new Properties();
props.put("myAge", "99");
ppc.setProperties(props);
ppc.setSystemTreePath("mySystemPath");
ppc.setUserTreePath("myUserPath");
Preferences.systemRoot().node("mySystemPath").node("mypath").put("myName", "myNameValue");
Preferences.systemRoot().node("mySystemPath/myotherpath").put("myTouchy", "myTouchyValue");
Preferences.userRoot().node("myUserPath/myotherpath").put("myTouchy", "myOtherTouchyValue");
ppc.afterPropertiesSet();
ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myNameValue", tb.getName());
assertEquals(99, tb.getAge());
assertEquals("myOtherTouchyValue", tb.getTouchy());
Preferences.userRoot().node("myUserPath/myotherpath").remove("myTouchy");
Preferences.systemRoot().node("mySystemPath/myotherpath").remove("myTouchy");
Preferences.systemRoot().node("mySystemPath/mypath").remove("myName");
}
private static class ConvertingOverrideConfigurer extends PropertyOverrideConfigurer {
protected String convertPropertyValue(String originalValue) {
return "X" + originalValue;
}
}
}

View File

@@ -0,0 +1,371 @@
/*
* Copyright 2002-2008 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.beans.factory.config;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.NestedCheckedException;
import org.springframework.core.NestedRuntimeException;
/**
* Unit tests for {@link ServiceLocatorFactoryBean}.
*
* @author Colin Sampaleanu
* @author Rick Evans
* @author Chris Beams
*/
public final class ServiceLocatorFactoryBeanTests {
private DefaultListableBeanFactory bf;
@Before
public void setUp() {
bf = new DefaultListableBeanFactory();
}
@Test
public void testNoArgGetter() {
bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition());
bf.registerBeanDefinition("factory",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestServiceLocator.class)
.getBeanDefinition());
TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory");
TestService testService = factory.getTestService();
assertNotNull(testService);
}
@Test
public void testErrorOnTooManyOrTooFew() throws Exception {
bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition());
bf.registerBeanDefinition("testServiceInstance2", genericBeanDefinition(TestService.class).getBeanDefinition());
bf.registerBeanDefinition("factory",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestServiceLocator.class)
.getBeanDefinition());
bf.registerBeanDefinition("factory2",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestServiceLocator2.class)
.getBeanDefinition());
bf.registerBeanDefinition("factory3",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestService2Locator.class)
.getBeanDefinition());
try {
TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory");
factory.getTestService();
fail("Must fail on more than one matching type");
} catch (NoSuchBeanDefinitionException ex) { /* expected */ }
try {
TestServiceLocator2 factory = (TestServiceLocator2) bf.getBean("factory2");
factory.getTestService(null);
fail("Must fail on more than one matching type");
} catch (NoSuchBeanDefinitionException ex) { /* expected */ }
try {
TestService2Locator factory = (TestService2Locator) bf.getBean("factory3");
factory.getTestService();
fail("Must fail on no matching types");
} catch (NoSuchBeanDefinitionException ex) { /* expected */ }
}
@Test
public void testErrorOnTooManyOrTooFewWithCustomServiceLocatorException() {
bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition());
bf.registerBeanDefinition("testServiceInstance2", genericBeanDefinition(TestService.class).getBeanDefinition());
bf.registerBeanDefinition("factory",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestServiceLocator.class)
.addPropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException1.class)
.getBeanDefinition());
bf.registerBeanDefinition("factory2",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestServiceLocator2.class)
.addPropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException2.class)
.getBeanDefinition());
bf.registerBeanDefinition("factory3",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestService2Locator.class)
.addPropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException3.class)
.getBeanDefinition());
try {
TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory");
factory.getTestService();
fail("Must fail on more than one matching type");
}
catch (CustomServiceLocatorException1 expected) {
assertTrue(expected.getCause() instanceof NoSuchBeanDefinitionException);
}
try {
TestServiceLocator2 factory2 = (TestServiceLocator2) bf.getBean("factory2");
factory2.getTestService(null);
fail("Must fail on more than one matching type");
}
catch (CustomServiceLocatorException2 expected) {
assertTrue(expected.getCause() instanceof NoSuchBeanDefinitionException);
}
try {
TestService2Locator factory3 = (TestService2Locator) bf.getBean("factory3");
factory3.getTestService();
fail("Must fail on no matching type");
} catch (CustomServiceLocatorException3 ex) { /* expected */ }
}
@Test
public void testStringArgGetter() throws Exception {
bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition());
bf.registerBeanDefinition("factory",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestServiceLocator2.class)
.getBeanDefinition());
// test string-arg getter with null id
TestServiceLocator2 factory = (TestServiceLocator2) bf.getBean("factory");
@SuppressWarnings("unused")
TestService testBean = factory.getTestService(null);
// now test with explicit id
testBean = factory.getTestService("testService");
// now verify failure on bad id
try {
factory.getTestService("bogusTestService");
fail("Illegal operation allowed");
} catch (NoSuchBeanDefinitionException ex) { /* expected */ }
}
@Ignore @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory
public void testCombinedLocatorInterface() {
bf.registerBeanDefinition("testService", genericBeanDefinition(TestService.class).getBeanDefinition());
bf.registerAlias("testService", "1");
bf.registerBeanDefinition("factory",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class)
.getBeanDefinition());
// StaticApplicationContext ctx = new StaticApplicationContext();
// ctx.registerPrototype("testService", TestService.class, new MutablePropertyValues());
// ctx.registerAlias("testService", "1");
// MutablePropertyValues mpv = new MutablePropertyValues();
// mpv.addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class);
// ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv);
// ctx.refresh();
TestServiceLocator3 factory = (TestServiceLocator3) bf.getBean("factory");
TestService testBean1 = factory.getTestService();
TestService testBean2 = factory.getTestService("testService");
TestService testBean3 = factory.getTestService(1);
TestService testBean4 = factory.someFactoryMethod();
assertNotSame(testBean1, testBean2);
assertNotSame(testBean1, testBean3);
assertNotSame(testBean1, testBean4);
assertNotSame(testBean2, testBean3);
assertNotSame(testBean2, testBean4);
assertNotSame(testBean3, testBean4);
assertTrue(factory.toString().indexOf("TestServiceLocator3") != -1);
}
@Ignore @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory
public void testServiceMappings() {
bf.registerBeanDefinition("testService1", genericBeanDefinition(TestService.class).getBeanDefinition());
bf.registerBeanDefinition("testService2", genericBeanDefinition(ExtendedTestService.class).getBeanDefinition());
bf.registerBeanDefinition("factory",
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class)
.addPropertyValue("serviceMappings", "=testService1\n1=testService1\n2=testService2")
.getBeanDefinition());
// StaticApplicationContext ctx = new StaticApplicationContext();
// ctx.registerPrototype("testService1", TestService.class, new MutablePropertyValues());
// ctx.registerPrototype("testService2", ExtendedTestService.class, new MutablePropertyValues());
// MutablePropertyValues mpv = new MutablePropertyValues();
// mpv.addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class);
// mpv.addPropertyValue("serviceMappings", "=testService1\n1=testService1\n2=testService2");
// ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv);
// ctx.refresh();
TestServiceLocator3 factory = (TestServiceLocator3) bf.getBean("factory");
TestService testBean1 = factory.getTestService();
TestService testBean2 = factory.getTestService("testService1");
TestService testBean3 = factory.getTestService(1);
TestService testBean4 = factory.getTestService(2);
assertNotSame(testBean1, testBean2);
assertNotSame(testBean1, testBean3);
assertNotSame(testBean1, testBean4);
assertNotSame(testBean2, testBean3);
assertNotSame(testBean2, testBean4);
assertNotSame(testBean3, testBean4);
assertFalse(testBean1 instanceof ExtendedTestService);
assertFalse(testBean2 instanceof ExtendedTestService);
assertFalse(testBean3 instanceof ExtendedTestService);
assertTrue(testBean4 instanceof ExtendedTestService);
}
@Test(expected=IllegalArgumentException.class)
public void testNoServiceLocatorInterfaceSupplied() throws Exception {
new ServiceLocatorFactoryBean().afterPropertiesSet();
}
@Test(expected=IllegalArgumentException.class)
public void testWhenServiceLocatorInterfaceIsNotAnInterfaceType() throws Exception {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setServiceLocatorInterface(getClass());
factory.afterPropertiesSet();
// should throw, bad (non-interface-type) serviceLocator interface supplied
}
@Test(expected=IllegalArgumentException.class)
public void testWhenServiceLocatorExceptionClassToExceptionTypeWithOnlyNoArgCtor() throws Exception {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setServiceLocatorExceptionClass(ExceptionClassWithOnlyZeroArgCtor.class);
// should throw, bad (invalid-Exception-type) serviceLocatorException class supplied
}
@Test(expected=IllegalArgumentException.class)
public void testWhenServiceLocatorExceptionClassIsNotAnExceptionSubclass() throws Exception {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setServiceLocatorExceptionClass(getClass());
// should throw, bad (non-Exception-type) serviceLocatorException class supplied
}
@Test(expected=UnsupportedOperationException.class)
public void testWhenServiceLocatorMethodCalledWithTooManyParameters() throws Exception {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setServiceLocatorInterface(ServiceLocatorInterfaceWithExtraNonCompliantMethod.class);
factory.afterPropertiesSet();
ServiceLocatorInterfaceWithExtraNonCompliantMethod locator = (ServiceLocatorInterfaceWithExtraNonCompliantMethod) factory.getObject();
locator.getTestService("not", "allowed"); //bad method (too many args, doesn't obey class contract)
}
@Test
public void testRequiresListableBeanFactoryAndChokesOnAnythingElse() throws Exception {
final BeanFactory beanFactory = createMock(BeanFactory.class);
replay(beanFactory);
try {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setBeanFactory(beanFactory);
} catch (FatalBeanException ex) {
// expected
}
verify(beanFactory);
}
public static class TestService {
}
public static class ExtendedTestService extends TestService {
}
public static class TestService2 {
}
public static interface TestServiceLocator {
TestService getTestService();
}
public static interface TestServiceLocator2 {
TestService getTestService(String id) throws CustomServiceLocatorException2;
}
public static interface TestServiceLocator3 {
TestService getTestService();
TestService getTestService(String id);
TestService getTestService(int id);
TestService someFactoryMethod();
}
public static interface TestService2Locator {
TestService2 getTestService() throws CustomServiceLocatorException3;
}
public static interface ServiceLocatorInterfaceWithExtraNonCompliantMethod {
TestService2 getTestService();
TestService2 getTestService(String serviceName, String defaultNotAllowedParameter);
}
@SuppressWarnings("serial")
public static class CustomServiceLocatorException1 extends NestedRuntimeException {
public CustomServiceLocatorException1(String message, Throwable cause) {
super(message, cause);
}
}
@SuppressWarnings("serial")
public static class CustomServiceLocatorException2 extends NestedCheckedException {
public CustomServiceLocatorException2(Throwable cause) {
super("", cause);
}
}
@SuppressWarnings("serial")
public static class CustomServiceLocatorException3 extends NestedCheckedException {
public CustomServiceLocatorException3(String message) {
super(message);
}
}
@SuppressWarnings("serial")
public static class ExceptionClassWithOnlyZeroArgCtor extends Exception {
}
}

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<bean id="usesScope" class="test.beans.TestBean" scope="myScope"/>
</beans>

View File

@@ -0,0 +1,84 @@
/*
* Copyright 2002-2008 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.beans.factory.config;
import static org.junit.Assert.*;
import static test.util.TestResourceUtils.qualifiedResource;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;
import test.beans.TestBean;
/**
* Simple test to illustrate and verify scope usage.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
*/
public final class SimpleScopeTests {
private static final Resource CONTEXT = qualifiedResource(SimpleScopeTests.class, "context.xml");
private DefaultListableBeanFactory beanFactory;
@Before
public void setUp() {
beanFactory = new DefaultListableBeanFactory();
Scope scope = new NoOpScope() {
private int index;
private List<TestBean> objects = new LinkedList<TestBean>(); {
objects.add(new TestBean());
objects.add(new TestBean());
}
public Object get(String name, ObjectFactory<?> objectFactory) {
if (index >= objects.size()) {
index = 0;
}
return objects.get(index++);
}
};
beanFactory.registerScope("myScope", scope);
String[] scopeNames = beanFactory.getRegisteredScopeNames();
assertEquals(1, scopeNames.length);
assertEquals("myScope", scopeNames[0]);
assertSame(scope, beanFactory.getRegisteredScope("myScope"));
XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(beanFactory);
xbdr.loadBeanDefinitions(CONTEXT);
}
@Test
public void testCanGetScopedObject() {
TestBean tb1 = (TestBean) beanFactory.getBean("usesScope");
TestBean tb2 = (TestBean) beanFactory.getBean("usesScope");
assertNotSame(tb1, tb2);
TestBean tb3 = (TestBean) beanFactory.getBean("usesScope");
assertSame(tb3, tb1);
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright 2002-2008 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.beans.factory.config;
import org.springframework.beans.factory.ObjectFactory;
/**
* Shared test types for this package.
*
* @author Chris Beams
*/
final class TestTypes {}
/**
* @author Juergen Hoeller
*/
class NoOpScope implements Scope {
public Object get(String name, ObjectFactory<?> objectFactory) {
throw new UnsupportedOperationException();
}
public Object remove(String name) {
throw new UnsupportedOperationException();
}
public void registerDestructionCallback(String name, Runnable callback) {
}
public Object resolveContextualObject(String key) {
return null;
}
public String getConversationId() {
return null;
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2008 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.beans.factory.parsing;
import org.junit.Test;
/**
* Unit tests for {@link ConstructorArgumentEntry}.
*
* @author Rick Evans
* @author Chris Beams
*/
public final class ConstructorArgumentEntryTests {
@Test(expected=IllegalArgumentException.class)
public void testCtorBailsOnNegativeCtorIndexArgument() {
new ConstructorArgumentEntry(-1);
}
}

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="invalidClass" class="some.class.that.does.not.Exist"/>
<bean id="invalidMapDefinition" class="test.beans.TestBean">
<property name="someMap">
<map>
<entry/>
</map>
</property>
</bean>
<bean id="nestedBeanErrors" class="test.beans.TestBean">
<property name="spouse">
<bean class="test.beans.TestBean">
<property name="someMap">
<map>
<entry/>
</map>
</property>
</bean>
</property>
</bean>
<bean id="validBean" class="test.beans.TestBean"/>
</beans>

View File

@@ -0,0 +1,97 @@
/*
* Copyright 2002-2008 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.beans.factory.parsing;
import static org.junit.Assert.*;
import static test.util.TestResourceUtils.qualifiedResource;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;
import test.beans.TestBean;
/**
* @author Rob Harrop
* @author Chris Beams
* @since 2.0
*/
public final class CustomProblemReporterTests {
private static final Resource CONTEXT = qualifiedResource(CustomProblemReporterTests.class, "context.xml");
private CollatingProblemReporter problemReporter;
private DefaultListableBeanFactory beanFactory;
private XmlBeanDefinitionReader reader;
@Before
public void setUp() {
this.problemReporter = new CollatingProblemReporter();
this.beanFactory = new DefaultListableBeanFactory();
this.reader = new XmlBeanDefinitionReader(this.beanFactory);
this.reader.setProblemReporter(this.problemReporter);
}
@Test
public void testErrorsAreCollated() {
this.reader.loadBeanDefinitions(CONTEXT);
assertEquals("Incorrect number of errors collated", 4, this.problemReporter.getErrors().length);
TestBean bean = (TestBean) this.beanFactory.getBean("validBean");
assertNotNull(bean);
}
private static class CollatingProblemReporter implements ProblemReporter {
private List<Problem> errors = new ArrayList<Problem>();
private List<Problem> warnings = new ArrayList<Problem>();
public void fatal(Problem problem) {
throw new BeanDefinitionParsingException(problem);
}
public void error(Problem problem) {
System.out.println(problem);
this.errors.add(problem);
}
public Problem[] getErrors() {
return this.errors.toArray(new Problem[this.errors.size()]);
}
public void warning(Problem problem) {
System.out.println(problem);
this.warnings.add(problem);
}
public Problem[] getWarnings() {
return this.warnings.toArray(new Problem[this.warnings.size()]);
}
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2002-2008 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.beans.factory.parsing;
import static org.easymock.EasyMock.*;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.springframework.core.io.DescriptiveResource;
/**
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public final class FailFastProblemReporterTests {
@Test(expected=BeanDefinitionParsingException.class)
public void testError() throws Exception {
FailFastProblemReporter reporter = new FailFastProblemReporter();
reporter.error(new Problem("VGER", new Location(new DescriptiveResource("here")),
null, new IllegalArgumentException()));
}
@Test
public void testWarn() throws Exception {
Problem problem = new Problem("VGER", new Location(new DescriptiveResource("here")),
null, new IllegalArgumentException());
Log log = createMock(Log.class);
log.warn(anyObject(), isA(IllegalArgumentException.class));
replay(log);
FailFastProblemReporter reporter = new FailFastProblemReporter();
reporter.setLogger(log);
reporter.warning(problem);
verify(log);
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2002-2008 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.beans.factory.parsing;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* @author Rick Evans
* @author Chris Beams
*/
public final class NullSourceExtractorTests {
@Test
public void testPassThroughContract() throws Exception {
Object source = new Object();
Object extractedSource = new NullSourceExtractor().extractSource(source, null);
assertNull("The contract of NullSourceExtractor states that the extraction *always* return null", extractedSource);
}
@Test
public void testPassThroughContractEvenWithNull() throws Exception {
Object extractedSource = new NullSourceExtractor().extractSource(null, null);
assertNull("The contract of NullSourceExtractor states that the extraction *always* return null", extractedSource);
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2002-2006 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.beans.factory.parsing;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* @author Rob Harrop
* @author Chris Beams
* @since 2.0
*/
public class ParseStateTests {
@Test
public void testSimple() throws Exception {
MockEntry entry = new MockEntry();
ParseState parseState = new ParseState();
parseState.push(entry);
assertEquals("Incorrect peek value.", entry, parseState.peek());
parseState.pop();
assertNull("Should get null on peek()", parseState.peek());
}
@Test
public void testNesting() throws Exception {
MockEntry one = new MockEntry();
MockEntry two = new MockEntry();
MockEntry three = new MockEntry();
ParseState parseState = new ParseState();
parseState.push(one);
assertEquals(one, parseState.peek());
parseState.push(two);
assertEquals(two, parseState.peek());
parseState.push(three);
assertEquals(three, parseState.peek());
parseState.pop();
assertEquals(two, parseState.peek());
parseState.pop();
assertEquals(one, parseState.peek());
}
@Test
public void testSnapshot() throws Exception {
MockEntry entry = new MockEntry();
ParseState original = new ParseState();
original.push(entry);
ParseState snapshot = original.snapshot();
original.push(new MockEntry());
assertEquals("Snapshot should not have been modified.", entry, snapshot.peek());
}
private static class MockEntry implements ParseState.Entry {
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2008 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.beans.factory.parsing;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Unit tests for {@link PassThroughSourceExtractor}.
*
* @author Rick Evans
* @author Chris Beams
*/
public final class PassThroughSourceExtractorTests {
@Test
public void testPassThroughContract() throws Exception {
Object source = new Object();
Object extractedSource = new PassThroughSourceExtractor().extractSource(source, null);
assertSame("The contract of PassThroughSourceExtractor states that the supplied " +
"source object *must* be returned as-is", source, extractedSource);
}
@Test
public void testPassThroughContractEvenWithNull() throws Exception {
Object extractedSource = new PassThroughSourceExtractor().extractSource(null, null);
assertNull("The contract of PassThroughSourceExtractor states that the supplied " +
"source object *must* be returned as-is (even if null)", extractedSource);
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2008 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.beans.factory.parsing;
import org.junit.Test;
/**
* Unit tests for {@link PropertyEntry}.
*
* @author Rick Evans
* @author Chris Beams
*/
public final class PropertyEntryTests {
@Test(expected=IllegalArgumentException.class)
public void testCtorBailsOnNullPropertyNameArgument() throws Exception {
new PropertyEntry(null);
}
@Test(expected=IllegalArgumentException.class)
public void testCtorBailsOnEmptyPropertyNameArgument() throws Exception {
new PropertyEntry("");
}
@Test(expected=IllegalArgumentException.class)
public void testCtorBailsOnWhitespacedPropertyNameArgument() throws Exception {
new PropertyEntry("\t ");
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2002-2007 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.beans.factory.serviceloader;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.ServiceLoader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.JdkVersion;
/**
* @author Juergen Hoeller
* @author Chris Beams
*/
public class ServiceLoaderTests {
@Test
public void testServiceLoaderFactoryBean() {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_16 ||
!ServiceLoader.load(DocumentBuilderFactory.class).iterator().hasNext()){
return;
}
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(ServiceLoaderFactoryBean.class);
bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName());
bf.registerBeanDefinition("service", bd);
ServiceLoader<?> serviceLoader = (ServiceLoader<?>) bf.getBean("service");
assertTrue(serviceLoader.iterator().next() instanceof DocumentBuilderFactory);
}
@Test
public void testServiceFactoryBean() {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_16 ||
!ServiceLoader.load(DocumentBuilderFactory.class).iterator().hasNext()){
return;
}
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(ServiceFactoryBean.class);
bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName());
bf.registerBeanDefinition("service", bd);
assertTrue(bf.getBean("service") instanceof DocumentBuilderFactory);
}
@Test
public void testServiceListFactoryBean() {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_16 ||
!ServiceLoader.load(DocumentBuilderFactory.class).iterator().hasNext()){
return;
}
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(ServiceListFactoryBean.class);
bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName());
bf.registerBeanDefinition("service", bd);
List<?> serviceList = (List<?>) bf.getBean("service");
assertTrue(serviceList.get(0) instanceof DocumentBuilderFactory);
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2002-2007 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.beans.factory.support;
import java.util.Arrays;
import junit.framework.TestCase;
import test.beans.TestBean;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class BeanDefinitionBuilderTests extends TestCase {
public void testBeanClassWithSimpleProperty() {
String[] dependsOn = new String[] { "A", "B", "C" };
BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
bdb.setSingleton(false).addPropertyReference("age", "15");
for (int i = 0; i < dependsOn.length; i++) {
bdb.addDependsOn(dependsOn[i]);
}
RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition();
assertFalse(rbd.isSingleton());
assertEquals(TestBean.class, rbd.getBeanClass());
assertTrue("Depends on was added", Arrays.equals(dependsOn, rbd.getDependsOn()));
assertTrue(rbd.getPropertyValues().contains("age"));
}
public void testBeanClassWithFactoryMethod() {
BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class, "create");
RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition();
assertTrue(rbd.hasBeanClass());
assertEquals(TestBean.class, rbd.getBeanClass());
assertEquals("create", rbd.getFactoryMethodName());
}
public void testBeanClassName() {
BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class.getName());
RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition();
assertFalse(rbd.hasBeanClass());
assertEquals(TestBean.class.getName(), rbd.getBeanClassName());
}
public void testBeanClassNameWithFactoryMethod() {
BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class.getName(), "create");
RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition();
assertFalse(rbd.hasBeanClass());
assertEquals(TestBean.class.getName(), rbd.getBeanClassName());
assertEquals("create", rbd.getFactoryMethodName());
}
}

View File

@@ -0,0 +1,135 @@
/*
* Copyright 2002-2006 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.beans.factory.support;
import junit.framework.TestCase;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import test.beans.TestBean;
/**
* @author Juergen Hoeller
*/
public class BeanDefinitionTests extends TestCase {
public void testBeanDefinitionEquality() {
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setAbstract(true);
bd.setLazyInit(true);
bd.setScope("request");
RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class);
assertTrue(!bd.equals(otherBd));
assertTrue(!otherBd.equals(bd));
otherBd.setAbstract(true);
otherBd.setLazyInit(true);
otherBd.setScope("request");
assertTrue(bd.equals(otherBd));
assertTrue(otherBd.equals(bd));
assertTrue(bd.hashCode() == otherBd.hashCode());
}
public void testBeanDefinitionEqualityWithPropertyValues() {
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.getPropertyValues().add("name", "myName");
bd.getPropertyValues().add("age", "99");
RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class);
otherBd.getPropertyValues().add("name", "myName");
assertTrue(!bd.equals(otherBd));
assertTrue(!otherBd.equals(bd));
otherBd.getPropertyValues().add("age", "11");
assertTrue(!bd.equals(otherBd));
assertTrue(!otherBd.equals(bd));
otherBd.getPropertyValues().add("age", "99");
assertTrue(bd.equals(otherBd));
assertTrue(otherBd.equals(bd));
assertTrue(bd.hashCode() == otherBd.hashCode());
}
public void testBeanDefinitionEqualityWithConstructorArguments() {
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.getConstructorArgumentValues().addGenericArgumentValue("test");
bd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5));
RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class);
otherBd.getConstructorArgumentValues().addGenericArgumentValue("test");
assertTrue(!bd.equals(otherBd));
assertTrue(!otherBd.equals(bd));
otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(9));
assertTrue(!bd.equals(otherBd));
assertTrue(!otherBd.equals(bd));
otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5));
assertTrue(bd.equals(otherBd));
assertTrue(otherBd.equals(bd));
assertTrue(bd.hashCode() == otherBd.hashCode());
}
public void testBeanDefinitionEqualityWithTypedConstructorArguments() {
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.getConstructorArgumentValues().addGenericArgumentValue("test", "int");
bd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5), "long");
RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class);
otherBd.getConstructorArgumentValues().addGenericArgumentValue("test", "int");
otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5));
assertTrue(!bd.equals(otherBd));
assertTrue(!otherBd.equals(bd));
otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5), "int");
assertTrue(!bd.equals(otherBd));
assertTrue(!otherBd.equals(bd));
otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5), "long");
assertTrue(bd.equals(otherBd));
assertTrue(otherBd.equals(bd));
assertTrue(bd.hashCode() == otherBd.hashCode());
}
public void testBeanDefinitionHolderEquality() {
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setAbstract(true);
bd.setLazyInit(true);
bd.setScope("request");
BeanDefinitionHolder holder = new BeanDefinitionHolder(bd, "bd");
RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class);
assertTrue(!bd.equals(otherBd));
assertTrue(!otherBd.equals(bd));
otherBd.setAbstract(true);
otherBd.setLazyInit(true);
otherBd.setScope("request");
BeanDefinitionHolder otherHolder = new BeanDefinitionHolder(bd, "bd");
assertTrue(holder.equals(otherHolder));
assertTrue(otherHolder.equals(holder));
assertTrue(holder.hashCode() == otherHolder.hashCode());
}
public void testBeanDefinitionMerging() {
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.getConstructorArgumentValues().addGenericArgumentValue("test");
bd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5));
bd.getPropertyValues().add("name", "myName");
bd.getPropertyValues().add("age", "99");
ChildBeanDefinition childBd = new ChildBeanDefinition("bd");
RootBeanDefinition mergedBd = new RootBeanDefinition(bd);
mergedBd.overrideFrom(childBd);
assertEquals(2, mergedBd.getConstructorArgumentValues().getArgumentCount());
assertEquals(2, mergedBd.getPropertyValues().size());
assertEquals(bd, mergedBd);
mergedBd.getConstructorArgumentValues().getArgumentValue(1, null).setValue(new Integer(9));
assertEquals(new Integer(5), bd.getConstructorArgumentValues().getArgumentValue(1, null).getValue());
}
}

View File

@@ -0,0 +1,666 @@
/*
* 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.beans.factory.support;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.*;
import org.junit.Test;
import test.beans.GenericBean;
import test.beans.GenericIntegerBean;
import test.beans.GenericSetOfIntegerBean;
import test.beans.TestBean;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.UrlResource;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @since 20.01.2006
*/
public class BeanFactoryGenericsTests {
@Test
public void testGenericSetProperty() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Set<String> input = new HashSet<String>();
input.add("4");
input.add("5");
rbd.getPropertyValues().add("integerSet", input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
}
@Test
public void testGenericListProperty() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
List<String> input = new ArrayList<String>();
input.add("http://localhost:8080");
input.add("http://localhost:9090");
rbd.getPropertyValues().add("resourceList", input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
@Test
public void testGenericListPropertyWithAutowiring() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerSingleton("resource1", new UrlResource("http://localhost:8080"));
bf.registerSingleton("resource2", new UrlResource("http://localhost:9090"));
RootBeanDefinition rbd = new RootBeanDefinition(GenericIntegerBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE);
bf.registerBeanDefinition("genericBean", rbd);
GenericIntegerBean gb = (GenericIntegerBean) bf.getBean("genericBean");
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
@Test
public void testGenericListPropertyWithInvalidElementType() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericIntegerBean.class);
List input = new ArrayList();
input.add(1);
rbd.getPropertyValues().add("testBeanList", input);
bf.registerBeanDefinition("genericBean", rbd);
try {
bf.getBean("genericBean");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("genericBean") && ex.getMessage().contains("testBeanList[0]"));
assertTrue(ex.getMessage().contains(TestBean.class.getName()) && ex.getMessage().contains("Integer"));
}
}
@Test
public void testGenericListPropertyWithOptionalAutowiring() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertNull(gb.getResourceList());
}
@Test
public void testGenericMapProperty() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<String, String> input = new HashMap<String, String>();
input.put("4", "5");
input.put("6", "7");
rbd.getPropertyValues().add("shortMap", input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
}
@Test
public void testGenericListOfArraysProperty() throws MalformedURLException {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("genericBeanTests.xml", getClass()));
GenericBean<?> gb = (GenericBean<?>) bf.getBean("listOfArrays");
assertEquals(1, gb.getListOfArrays().size());
String[] array = gb.getListOfArrays().get(0);
assertEquals(2, array.length);
assertEquals("value1", array[0]);
assertEquals("value2", array[1]);
}
@Test
public void testGenericSetConstructor() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Set<String> input = new HashSet<String>();
input.add("4");
input.add("5");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
}
@Test
public void testGenericSetConstructorWithAutowiring() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerSingleton("integer1", new Integer(4));
bf.registerSingleton("integer2", new Integer(5));
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class, RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
}
@Test
public void testGenericSetConstructorWithOptionalAutowiring() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class, RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertNull(gb.getIntegerSet());
}
@Test
public void testGenericSetListConstructor() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Set<String> input = new HashSet<String>();
input.add("4");
input.add("5");
List<String> input2 = new ArrayList<String>();
input2.add("http://localhost:8080");
input2.add("http://localhost:9090");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input2);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
@Test
public void testGenericSetListConstructorWithAutowiring() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerSingleton("integer1", new Integer(4));
bf.registerSingleton("integer2", new Integer(5));
bf.registerSingleton("resource1", new UrlResource("http://localhost:8080"));
bf.registerSingleton("resource2", new UrlResource("http://localhost:9090"));
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class, RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
@Test
public void testGenericSetListConstructorWithOptionalAutowiring() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerSingleton("resource1", new UrlResource("http://localhost:8080"));
bf.registerSingleton("resource2", new UrlResource("http://localhost:9090"));
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class, RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertNull(gb.getIntegerSet());
assertNull(gb.getResourceList());
}
@Test
public void testGenericSetMapConstructor() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Set<String> input = new HashSet<String>();
input.add("4");
input.add("5");
Map<String, String> input2 = new HashMap<String, String>();
input2.put("4", "5");
input2.put("6", "7");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input2);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
}
@Test
public void testGenericMapResourceConstructor() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<String, String> input = new HashMap<String, String>();
input.put("4", "5");
input.put("6", "7");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue("http://localhost:8080");
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
}
@Test
public void testGenericMapMapConstructor() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<String, String> input = new HashMap<String, String>();
input.put("1", "0");
input.put("2", "3");
Map<String, String> input2 = new HashMap<String, String>();
input2.put("4", "5");
input2.put("6", "7");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input2);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertNotSame(gb.getPlainMap(), gb.getShortMap());
assertEquals(2, gb.getPlainMap().size());
assertEquals("0", gb.getPlainMap().get("1"));
assertEquals("3", gb.getPlainMap().get("2"));
assertEquals(2, gb.getShortMap().size());
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
}
@Test
public void testGenericMapMapConstructorWithSameRefAndConversion() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<String, String> input = new HashMap<String, String>();
input.put("1", "0");
input.put("2", "3");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertNotSame(gb.getPlainMap(), gb.getShortMap());
assertEquals(2, gb.getPlainMap().size());
assertEquals("0", gb.getPlainMap().get("1"));
assertEquals("3", gb.getPlainMap().get("2"));
assertEquals(2, gb.getShortMap().size());
assertEquals(new Integer(0), gb.getShortMap().get(new Short("1")));
assertEquals(new Integer(3), gb.getShortMap().get(new Short("2")));
}
@Test
public void testGenericMapMapConstructorWithSameRefAndNoConversion() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<Short, Integer> input = new HashMap<Short, Integer>();
input.put(new Short((short) 1), new Integer(0));
input.put(new Short((short) 2), new Integer(3));
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertSame(gb.getPlainMap(), gb.getShortMap());
assertEquals(2, gb.getShortMap().size());
assertEquals(new Integer(0), gb.getShortMap().get(new Short("1")));
assertEquals(new Integer(3), gb.getShortMap().get(new Short("2")));
}
@Test
public void testGenericMapWithKeyTypeConstructor() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<String, String> input = new HashMap<String, String>();
input.put("4", "5");
input.put("6", "7");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertEquals("5", gb.getLongMap().get(new Long("4")));
assertEquals("7", gb.getLongMap().get(new Long("6")));
}
@Test
public void testGenericMapWithCollectionValueConstructor() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
}
});
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<String, AbstractCollection<?>> input = new HashMap<String, AbstractCollection<?>>();
HashSet<Integer> value1 = new HashSet<Integer>();
value1.add(new Integer(1));
input.put("1", value1);
ArrayList<Boolean> value2 = new ArrayList<Boolean>();
value2.add(Boolean.TRUE);
input.put("2", value2);
rbd.getConstructorArgumentValues().addGenericArgumentValue(Boolean.TRUE);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet);
assertTrue(gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList);
}
@Test
public void testGenericSetFactoryMethod() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
Set<String> input = new HashSet<String>();
input.add("4");
input.add("5");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
}
@Test
public void testGenericSetListFactoryMethod() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
Set<String> input = new HashSet<String>();
input.add("4");
input.add("5");
List<String> input2 = new ArrayList<String>();
input2.add("http://localhost:8080");
input2.add("http://localhost:9090");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input2);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
@Test
public void testGenericSetMapFactoryMethod() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
Set<String> input = new HashSet<String>();
input.add("4");
input.add("5");
Map<String, String> input2 = new HashMap<String, String>();
input2.put("4", "5");
input2.put("6", "7");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input2);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
}
@Test
public void testGenericMapResourceFactoryMethod() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
Map<String, String> input = new HashMap<String, String>();
input.put("4", "5");
input.put("6", "7");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue("http://localhost:8080");
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
}
@Test
public void testGenericMapMapFactoryMethod() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
Map<String, String> input = new HashMap<String, String>();
input.put("1", "0");
input.put("2", "3");
Map<String, String> input2 = new HashMap<String, String>();
input2.put("4", "5");
input2.put("6", "7");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input2);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertEquals("0", gb.getPlainMap().get("1"));
assertEquals("3", gb.getPlainMap().get("2"));
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
}
@Test
public void testGenericMapWithKeyTypeFactoryMethod() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
Map<String, String> input = new HashMap<String, String>();
input.put("4", "5");
input.put("6", "7");
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertEquals("5", gb.getLongMap().get(new Long("4")));
assertEquals("7", gb.getLongMap().get(new Long("6")));
}
@Test
public void testGenericMapWithCollectionValueFactoryMethod() throws MalformedURLException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
}
});
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
Map<String, AbstractCollection<?>> input = new HashMap<String, AbstractCollection<?>>();
HashSet<Integer> value1 = new HashSet<Integer>();
value1.add(new Integer(1));
input.put("1", value1);
ArrayList<Boolean> value2 = new ArrayList<Boolean>();
value2.add(Boolean.TRUE);
input.put("2", value2);
rbd.getConstructorArgumentValues().addGenericArgumentValue(Boolean.TRUE);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet);
assertTrue(gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList);
}
@Test
public void testGenericListBean() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("genericBeanTests.xml", getClass()));
List<?> list = (List<?>) bf.getBean("list");
assertEquals(1, list.size());
assertEquals(new URL("http://localhost:8080"), list.get(0));
}
@Test
public void testGenericSetBean() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("genericBeanTests.xml", getClass()));
Set<?> set = (Set<?>) bf.getBean("set");
assertEquals(1, set.size());
assertEquals(new URL("http://localhost:8080"), set.iterator().next());
}
@Test
public void testGenericMapBean() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("genericBeanTests.xml", getClass()));
Map<?, ?> map = (Map<?, ?>) bf.getBean("map");
assertEquals(1, map.size());
assertEquals(new Integer(10), map.keySet().iterator().next());
assertEquals(new URL("http://localhost:8080"), map.values().iterator().next());
}
@Test
public void testGenericallyTypedIntegerBean() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("genericBeanTests.xml", getClass()));
GenericIntegerBean gb = (GenericIntegerBean) bf.getBean("integerBean");
assertEquals(new Integer(10), gb.getGenericProperty());
assertEquals(new Integer(20), gb.getGenericListProperty().get(0));
assertEquals(new Integer(30), gb.getGenericListProperty().get(1));
}
@Test
public void testGenericallyTypedSetOfIntegerBean() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("genericBeanTests.xml", getClass()));
GenericSetOfIntegerBean gb = (GenericSetOfIntegerBean) bf.getBean("setOfIntegerBean");
assertEquals(new Integer(10), gb.getGenericProperty().iterator().next());
assertEquals(new Integer(20), gb.getGenericListProperty().get(0).iterator().next());
assertEquals(new Integer(30), gb.getGenericListProperty().get(1).iterator().next());
}
@Test
public void testSetBean() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("genericBeanTests.xml", getClass()));
UrlSet us = (UrlSet) bf.getBean("setBean");
assertEquals(1, us.size());
assertEquals(new URL("http://www.springframework.org"), us.iterator().next());
}
@SuppressWarnings("serial")
public static class NamedUrlList extends LinkedList<URL> {
}
@SuppressWarnings("serial")
public static class NamedUrlSet extends HashSet<URL> {
}
@SuppressWarnings("serial")
public static class NamedUrlMap extends HashMap<Integer, URL> {
}
public static class CollectionDependentBean {
public CollectionDependentBean(NamedUrlList list, NamedUrlSet set, NamedUrlMap map) {
assertEquals(1, list.size());
assertEquals(1, set.size());
assertEquals(1, map.size());
}
}
@SuppressWarnings("serial")
public static class UrlSet extends HashSet<URL> {
public UrlSet() {
super();
}
public UrlSet(Set<? extends URL> urls) {
super();
}
public void setUrlNames(Set<URI> urlNames) throws MalformedURLException {
for (URI urlName : urlNames) {
add(urlName.toURL());
}
}
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2002-2008 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.beans.factory.support;
import junit.framework.TestCase;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import test.beans.TestBean;
/**
* @author Rob Harrop
*/
public class DefinitionMetadataEqualsHashCodeTests extends TestCase {
public void testRootBeanDefinitionEqualsAndHashCode() throws Exception {
RootBeanDefinition master = new RootBeanDefinition(TestBean.class);
RootBeanDefinition equal = new RootBeanDefinition(TestBean.class);
RootBeanDefinition notEqual = new RootBeanDefinition(String.class);
RootBeanDefinition subclass = new RootBeanDefinition(TestBean.class) {};
setBaseProperties(master);
setBaseProperties(equal);
setBaseProperties(notEqual);
setBaseProperties(subclass);
assertEqualsContract(master, equal, notEqual, subclass);
assertEquals("Hash code for equal instances should match", master.hashCode(), equal.hashCode());
}
public void testChildBeanDefinitionEqualsAndHashCode() throws Exception {
ChildBeanDefinition master = new ChildBeanDefinition("foo");
ChildBeanDefinition equal = new ChildBeanDefinition("foo");
ChildBeanDefinition notEqual = new ChildBeanDefinition("bar");
ChildBeanDefinition subclass = new ChildBeanDefinition("foo"){};
setBaseProperties(master);
setBaseProperties(equal);
setBaseProperties(notEqual);
setBaseProperties(subclass);
assertEqualsContract(master, equal, notEqual, subclass);
assertEquals("Hash code for equal instances should match", master.hashCode(), equal.hashCode());
}
public void testRuntimeBeanReference() throws Exception {
RuntimeBeanReference master = new RuntimeBeanReference("name");
RuntimeBeanReference equal = new RuntimeBeanReference("name");
RuntimeBeanReference notEqual = new RuntimeBeanReference("someOtherName");
RuntimeBeanReference subclass = new RuntimeBeanReference("name"){};
assertEqualsContract(master, equal, notEqual, subclass);
}
private void setBaseProperties(AbstractBeanDefinition definition) {
definition.setAbstract(true);
definition.setAttribute("foo", "bar");
definition.setAutowireCandidate(false);
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
//definition.getConstructorArgumentValues().addGenericArgumentValue("foo");
definition.setDependencyCheck(AbstractBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
definition.setDependsOn(new String[]{"foo", "bar"});
definition.setDestroyMethodName("destroy");
definition.setEnforceDestroyMethod(false);
definition.setEnforceInitMethod(true);
definition.setFactoryBeanName("factoryBean");
definition.setFactoryMethodName("factoryMethod");
definition.setInitMethodName("init");
definition.setLazyInit(true);
definition.getMethodOverrides().addOverride(new LookupOverride("foo", "bar"));
definition.getMethodOverrides().addOverride(new ReplaceOverride("foo", "bar"));
definition.getPropertyValues().add("foo", "bar");
definition.setResourceDescription("desc");
definition.setRole(BeanDefinition.ROLE_APPLICATION);
definition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
definition.setSource("foo");
}
private void assertEqualsContract(Object master, Object equal, Object notEqual, Object subclass) {
assertEquals("Should be equal", master, equal);
assertFalse("Should not be equal", master.equals(notEqual));
assertEquals("Subclass should be equal", master, subclass);
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2002-2007 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.beans.factory.support;
import java.util.List;
import junit.framework.TestCase;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class ManagedListTests extends TestCase {
public void testMergeSunnyDay() {
ManagedList parent = new ManagedList();
parent.add("one");
parent.add("two");
ManagedList child = new ManagedList();
child.add("three");
child.setMergeEnabled(true);
List mergedList = (List) child.merge(parent);
assertEquals("merge() obviously did not work.", 3, mergedList.size());
}
public void testMergeWithNullParent() {
ManagedList child = new ManagedList();
child.add("one");
child.setMergeEnabled(true);
assertSame(child, child.merge(null));
}
public void testMergeNotAllowedWhenMergeNotEnabled() {
ManagedList child = new ManagedList();
try {
child.merge(null);
fail("Must have failed by this point (cannot merge() when the mergeEnabled property is false.");
}
catch (IllegalStateException expected) {
}
}
public void testMergeWithNonCompatibleParentType() {
ManagedList child = new ManagedList();
child.add("one");
child.setMergeEnabled(true);
try {
child.merge("hello");
fail("Must have failed by this point.");
}
catch (IllegalArgumentException expected) {
}
}
public void testMergeEmptyChild() {
ManagedList parent = new ManagedList();
parent.add("one");
parent.add("two");
ManagedList child = new ManagedList();
child.setMergeEnabled(true);
List mergedList = (List) child.merge(parent);
assertEquals("merge() obviously did not work.", 2, mergedList.size());
}
public void testMergeChildValuesOverrideTheParents() {
// doesn't make a whole lotta sense in the context of a list...
ManagedList parent = new ManagedList();
parent.add("one");
parent.add("two");
ManagedList child = new ManagedList();
child.add("one");
child.setMergeEnabled(true);
List mergedList = (List) child.merge(parent);
assertEquals("merge() obviously did not work.", 3, mergedList.size());
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2002-2007 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.beans.factory.support;
import java.util.Map;
import junit.framework.TestCase;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class ManagedMapTests extends TestCase {
public void testMergeSunnyDay() {
ManagedMap parent = new ManagedMap();
parent.put("one", "one");
parent.put("two", "two");
ManagedMap child = new ManagedMap();
child.put("three", "three");
child.setMergeEnabled(true);
Map mergedMap = (Map) child.merge(parent);
assertEquals("merge() obviously did not work.", 3, mergedMap.size());
}
public void testMergeWithNullParent() {
ManagedMap child = new ManagedMap();
child.setMergeEnabled(true);
assertSame(child, child.merge(null));
}
public void testMergeWithNonCompatibleParentType() {
ManagedMap map = new ManagedMap();
map.setMergeEnabled(true);
try {
map.merge("hello");
fail("Must have failed by this point.");
}
catch (IllegalArgumentException expected) {
}
}
public void testMergeNotAllowedWhenMergeNotEnabled() {
ManagedMap map = new ManagedMap();
try {
map.merge(null);
fail("Must have failed by this point (cannot merge() when the mergeEnabled property is false.");
}
catch (IllegalStateException expected) {
}
}
public void testMergeEmptyChild() {
ManagedMap parent = new ManagedMap();
parent.put("one", "one");
parent.put("two", "two");
ManagedMap child = new ManagedMap();
child.setMergeEnabled(true);
Map mergedMap = (Map) child.merge(parent);
assertEquals("merge() obviously did not work.", 2, mergedMap.size());
}
public void testMergeChildValuesOverrideTheParents() {
ManagedMap parent = new ManagedMap();
parent.put("one", "one");
parent.put("two", "two");
ManagedMap child = new ManagedMap();
child.put("one", "fork");
child.setMergeEnabled(true);
Map mergedMap = (Map) child.merge(parent);
// child value for 'one' must override parent value...
assertEquals("merge() obviously did not work.", 2, mergedMap.size());
assertEquals("Parent value not being overridden during merge().", "fork", mergedMap.get("one"));
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2002-2007 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.beans.factory.support;
import java.util.Map;
import junit.framework.TestCase;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class ManagedPropertiesTests extends TestCase {
public void testMergeSunnyDay() {
ManagedProperties parent = new ManagedProperties();
parent.setProperty("one", "one");
parent.setProperty("two", "two");
ManagedProperties child = new ManagedProperties();
child.setProperty("three", "three");
child.setMergeEnabled(true);
Map mergedMap = (Map) child.merge(parent);
assertEquals("merge() obviously did not work.", 3, mergedMap.size());
}
public void testMergeWithNullParent() {
ManagedProperties child = new ManagedProperties();
child.setMergeEnabled(true);
assertSame(child, child.merge(null));
}
public void testMergeWithNonCompatibleParentType() {
ManagedProperties map = new ManagedProperties();
map.setMergeEnabled(true);
try {
map.merge("hello");
fail("Must have failed by this point.");
}
catch (IllegalArgumentException expected) {
}
}
public void testMergeNotAllowedWhenMergeNotEnabled() {
ManagedProperties map = new ManagedProperties();
try {
map.merge(null);
fail("Must have failed by this point (cannot merge() when the mergeEnabled property is false.");
}
catch (IllegalStateException expected) {
}
}
public void testMergeEmptyChild() {
ManagedProperties parent = new ManagedProperties();
parent.setProperty("one", "one");
parent.setProperty("two", "two");
ManagedProperties child = new ManagedProperties();
child.setMergeEnabled(true);
Map mergedMap = (Map) child.merge(parent);
assertEquals("merge() obviously did not work.", 2, mergedMap.size());
}
public void testMergeChildValuesOverrideTheParents() {
ManagedProperties parent = new ManagedProperties();
parent.setProperty("one", "one");
parent.setProperty("two", "two");
ManagedProperties child = new ManagedProperties();
child.setProperty("one", "fork");
child.setMergeEnabled(true);
Map mergedMap = (Map) child.merge(parent);
// child value for 'one' must override parent value...
assertEquals("merge() obviously did not work.", 2, mergedMap.size());
assertEquals("Parent value not being overridden during merge().", "fork", mergedMap.get("one"));
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2002-2007 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.beans.factory.support;
import java.util.Set;
import junit.framework.TestCase;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class ManagedSetTests extends TestCase {
public void testMergeSunnyDay() {
ManagedSet parent = new ManagedSet();
parent.add("one");
parent.add("two");
ManagedSet child = new ManagedSet();
child.add("three");
child.setMergeEnabled(true);
Set mergedSet = (Set) child.merge(parent);
assertEquals("merge() obviously did not work.", 3, mergedSet.size());
}
public void testMergeWithNullParent() {
ManagedSet child = new ManagedSet();
child.add("one");
child.setMergeEnabled(true);
assertSame(child, child.merge(null));
}
public void testMergeNotAllowedWhenMergeNotEnabled() {
ManagedSet child = new ManagedSet();
try {
child.merge(null);
fail("Must have failed by this point (cannot merge() when the mergeEnabled property is false.");
}
catch (IllegalStateException expected) {
}
}
public void testMergeWithNonCompatibleParentType() {
ManagedSet child = new ManagedSet();
child.add("one");
child.setMergeEnabled(true);
try {
child.merge("hello");
fail("Must have failed by this point.");
}
catch (IllegalArgumentException expected) {
}
}
public void testMergeEmptyChild() {
ManagedSet parent = new ManagedSet();
parent.add("one");
parent.add("two");
ManagedSet child = new ManagedSet();
child.setMergeEnabled(true);
Set mergedSet = (Set) child.merge(parent);
assertEquals("merge() obviously did not work.", 2, mergedSet.size());
}
public void testMergeChildValuesOverrideTheParents() {
// asserts that the set contract is not violated during a merge() operation...
ManagedSet parent = new ManagedSet();
parent.add("one");
parent.add("two");
ManagedSet child = new ManagedSet();
child.add("one");
child.setMergeEnabled(true);
Set mergedSet = (Set) child.merge(parent);
assertEquals("merge() obviously did not work.", 2, mergedSet.size());
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2002-2006 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.beans.factory.support;
import junit.framework.TestCase;
import org.springframework.core.io.ClassPathResource;
import test.beans.TestBean;
/**
* @author Rob Harrop
*/
public class PropertiesBeanDefinitionReaderTests extends TestCase {
private DefaultListableBeanFactory beanFactory;
private PropertiesBeanDefinitionReader reader;
protected void setUp() throws Exception {
this.beanFactory = new DefaultListableBeanFactory();
this.reader = new PropertiesBeanDefinitionReader(beanFactory);
}
public void testWithSimpleConstructorArg() {
this.reader.loadBeanDefinitions(new ClassPathResource("simpleConstructorArg.properties", getClass()));
TestBean bean = (TestBean)this.beanFactory.getBean("testBean");
assertEquals("Rob Harrop", bean.getName());
}
public void testWithConstructorArgRef() throws Exception {
this.reader.loadBeanDefinitions(new ClassPathResource("refConstructorArg.properties", getClass()));
TestBean rob = (TestBean)this.beanFactory.getBean("rob");
TestBean sally = (TestBean)this.beanFactory.getBean("sally");
assertEquals(sally, rob.getSpouse());
}
public void testWithMultipleConstructorsArgs() throws Exception {
this.reader.loadBeanDefinitions(new ClassPathResource("multiConstructorArgs.properties", getClass()));
TestBean bean = (TestBean)this.beanFactory.getBean("testBean");
assertEquals("Rob Harrop", bean.getName());
assertEquals(23, bean.getAge());
}
}

View File

@@ -0,0 +1,249 @@
/*
* Copyright 2002-2008 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.beans.factory.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.util.ClassUtils;
/**
* @author Mark Fisher
* @author Juergen Hoeller
*/
public class QualifierAnnotationAutowireBeanFactoryTests {
private static final String JUERGEN = "juergen";
private static final String MARK = "mark";
@Test
public void testAutowireCandidateDefaultWithIrrelevantDescriptor() throws Exception {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
ConstructorArgumentValues cavs = new ConstructorArgumentValues();
cavs.addGenericArgumentValue(JUERGEN);
RootBeanDefinition rbd = new RootBeanDefinition(Person.class, cavs, null);
lbf.registerBeanDefinition(JUERGEN, rbd);
assertTrue(lbf.isAutowireCandidate(JUERGEN, null));
assertTrue(lbf.isAutowireCandidate(JUERGEN,
new DependencyDescriptor(Person.class.getDeclaredField("name"), false)));
assertTrue(lbf.isAutowireCandidate(JUERGEN,
new DependencyDescriptor(Person.class.getDeclaredField("name"), true)));
}
@Test
public void testAutowireCandidateExplicitlyFalseWithIrrelevantDescriptor() throws Exception {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
ConstructorArgumentValues cavs = new ConstructorArgumentValues();
cavs.addGenericArgumentValue(JUERGEN);
RootBeanDefinition rbd = new RootBeanDefinition(Person.class, cavs, null);
rbd.setAutowireCandidate(false);
lbf.registerBeanDefinition(JUERGEN, rbd);
assertFalse(lbf.isAutowireCandidate(JUERGEN, null));
assertFalse(lbf.isAutowireCandidate(JUERGEN,
new DependencyDescriptor(Person.class.getDeclaredField("name"), false)));
assertFalse(lbf.isAutowireCandidate(JUERGEN,
new DependencyDescriptor(Person.class.getDeclaredField("name"), true)));
}
@Ignore
@Test
public void testAutowireCandidateWithFieldDescriptor() throws Exception {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
cavs1.addGenericArgumentValue(JUERGEN);
RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
person1.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
lbf.registerBeanDefinition(JUERGEN, person1);
ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
cavs2.addGenericArgumentValue(MARK);
RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
lbf.registerBeanDefinition(MARK, person2);
DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(
QualifiedTestBean.class.getDeclaredField("qualified"), false);
DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor(
QualifiedTestBean.class.getDeclaredField("nonqualified"), false);
assertTrue(lbf.isAutowireCandidate(JUERGEN, null));
assertTrue(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor));
assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor));
assertTrue(lbf.isAutowireCandidate(MARK, null));
assertTrue(lbf.isAutowireCandidate(MARK, nonqualifiedDescriptor));
assertFalse(lbf.isAutowireCandidate(MARK, qualifiedDescriptor));
}
@Test
public void testAutowireCandidateExplicitlyFalseWithFieldDescriptor() throws Exception {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
ConstructorArgumentValues cavs = new ConstructorArgumentValues();
cavs.addGenericArgumentValue(JUERGEN);
RootBeanDefinition person = new RootBeanDefinition(Person.class, cavs, null);
person.setAutowireCandidate(false);
person.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
lbf.registerBeanDefinition(JUERGEN, person);
DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(
QualifiedTestBean.class.getDeclaredField("qualified"), false);
DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor(
QualifiedTestBean.class.getDeclaredField("nonqualified"), false);
assertFalse(lbf.isAutowireCandidate(JUERGEN, null));
assertFalse(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor));
assertFalse(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor));
}
@Test
public void testAutowireCandidateWithShortClassName() throws Exception {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
ConstructorArgumentValues cavs = new ConstructorArgumentValues();
cavs.addGenericArgumentValue(JUERGEN);
RootBeanDefinition person = new RootBeanDefinition(Person.class, cavs, null);
person.addQualifier(new AutowireCandidateQualifier(ClassUtils.getShortName(TestQualifier.class)));
lbf.registerBeanDefinition(JUERGEN, person);
DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(
QualifiedTestBean.class.getDeclaredField("qualified"), false);
DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor(
QualifiedTestBean.class.getDeclaredField("nonqualified"), false);
assertTrue(lbf.isAutowireCandidate(JUERGEN, null));
assertTrue(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor));
assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor));
}
@Ignore
@Test
public void testAutowireCandidateWithConstructorDescriptor() throws Exception {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
cavs1.addGenericArgumentValue(JUERGEN);
RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
person1.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
lbf.registerBeanDefinition(JUERGEN, person1);
ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
cavs2.addGenericArgumentValue(MARK);
RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
lbf.registerBeanDefinition(MARK, person2);
MethodParameter param = new MethodParameter(QualifiedTestBean.class.getDeclaredConstructor(Person.class), 0);
DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(param, false);
param.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
assertEquals("tpb", param.getParameterName());
assertTrue(lbf.isAutowireCandidate(JUERGEN, null));
assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor));
assertFalse(lbf.isAutowireCandidate(MARK, qualifiedDescriptor));
}
@Ignore
@Test
public void testAutowireCandidateWithMethodDescriptor() throws Exception {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
cavs1.addGenericArgumentValue(JUERGEN);
RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
person1.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
lbf.registerBeanDefinition(JUERGEN, person1);
ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
cavs2.addGenericArgumentValue(MARK);
RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
lbf.registerBeanDefinition(MARK, person2);
MethodParameter qualifiedParam =
new MethodParameter(QualifiedTestBean.class.getDeclaredMethod("autowireQualified", Person.class), 0);
MethodParameter nonqualifiedParam =
new MethodParameter(QualifiedTestBean.class.getDeclaredMethod("autowireNonqualified", Person.class), 0);
DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(qualifiedParam, false);
DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor(nonqualifiedParam, false);
qualifiedParam.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
assertEquals("tpb", qualifiedParam.getParameterName());
nonqualifiedParam.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
assertEquals("tpb", nonqualifiedParam.getParameterName());
assertTrue(lbf.isAutowireCandidate(JUERGEN, null));
assertTrue(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor));
assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor));
assertTrue(lbf.isAutowireCandidate(MARK, null));
assertTrue(lbf.isAutowireCandidate(MARK, nonqualifiedDescriptor));
assertFalse(lbf.isAutowireCandidate(MARK, qualifiedDescriptor));
}
@Test
public void testAutowireCandidateWithMultipleCandidatesDescriptor() throws Exception {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
cavs1.addGenericArgumentValue(JUERGEN);
RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
person1.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
lbf.registerBeanDefinition(JUERGEN, person1);
ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
cavs2.addGenericArgumentValue(MARK);
RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
person2.addQualifier(new AutowireCandidateQualifier(TestQualifier.class));
lbf.registerBeanDefinition(MARK, person2);
DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(
new MethodParameter(QualifiedTestBean.class.getDeclaredConstructor(Person.class), 0),
false);
assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor));
assertTrue(lbf.isAutowireCandidate(MARK, qualifiedDescriptor));
}
private static class QualifiedTestBean {
@TestQualifier
private Person qualified;
private Person nonqualified;
public QualifiedTestBean(@TestQualifier Person tpb) {
}
public void autowireQualified(@TestQualifier Person tpb) {
}
public void autowireNonqualified(Person tpb) {
}
}
private static class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
private static @interface TestQualifier {
}
}

View File

@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="listOfArrays" class="test.beans.GenericBean">
<property name="listOfArrays">
<list>
<list>
<value>value1</value>
<value>value2</value>
</list>
</list>
</property>
</bean>
<bean id="list" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList" value="http://localhost:8080"/>
<property name="targetListClass" value="org.springframework.beans.factory.support.BeanFactoryGenericsTests$NamedUrlList"/>
</bean>
<bean id="set" class="org.springframework.beans.factory.config.SetFactoryBean">
<property name="sourceSet" value="http://localhost:8080"/>
<property name="targetSetClass" value="org.springframework.beans.factory.support.BeanFactoryGenericsTests$NamedUrlSet"/>
</bean>
<bean id="map" class="org.springframework.beans.factory.config.MapFactoryBean">
<property name="sourceMap">
<map>
<entry key="10" value="http://localhost:8080"/>
</map>
</property>
<property name="targetMapClass" value="org.springframework.beans.factory.support.BeanFactoryGenericsTests$NamedUrlMap"/>
</bean>
<bean class="org.springframework.beans.factory.support.BeanFactoryGenericsTests$CollectionDependentBean">
<constructor-arg ref="list"/>
<constructor-arg ref="set"/>
<constructor-arg ref="map"/>
</bean>
<bean class="org.springframework.beans.factory.support.BeanFactoryGenericsTests$CollectionDependentBean"
autowire="constructor">
</bean>
<bean id="integerBean" class="test.beans.GenericIntegerBean">
<property name="genericProperty" value="10"/>
<property name="genericListProperty">
<list>
<value>20</value>
<value>30</value>
</list>
</property>
</bean>
<bean id="setOfIntegerBean" class="test.beans.GenericSetOfIntegerBean">
<property name="genericProperty" value="10"/>
<property name="genericListProperty">
<list>
<value>20</value>
<value>30</value>
</list>
</property>
</bean>
<bean id="setBean" class="org.springframework.beans.factory.support.BeanFactoryGenericsTests$UrlSet">
<property name="urlNames" value="http://www.springframework.org"/>
</bean>
</beans>

View File

@@ -0,0 +1,526 @@
/*
* 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.beans.factory.support.security;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.Policy;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.PropertyPermission;
import java.util.Set;
import javax.security.auth.AuthPermission;
import javax.security.auth.Subject;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.SmartFactoryBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.SecurityContextProvider;
import org.springframework.beans.factory.support.security.support.ConstructorBean;
import org.springframework.beans.factory.support.security.support.CustomCallbackBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
/**
* Security test case. Checks whether the container uses its privileges for its
* internal work but does not leak them when touching/calling user code.
*
*t The first half of the test case checks that permissions are downgraded when
* calling user code while the second half that the caller code permission get
* through and Spring doesn't override the permission stack.
*
* @author Costin Leau
*/
@org.junit.Ignore
public class CallbacksSecurityTests {
private XmlBeanFactory beanFactory;
private SecurityContextProvider provider;
private static class NonPrivilegedBean {
private String expectedName;
public static boolean destroyed = false;
public NonPrivilegedBean(String expected) {
this.expectedName = expected;
checkCurrentContext();
}
public void init() {
checkCurrentContext();
}
public void destroy() {
checkCurrentContext();
destroyed = true;
}
public void setProperty(Object value) {
checkCurrentContext();
}
public Object getProperty() {
checkCurrentContext();
return null;
}
public void setListProperty(Object value) {
checkCurrentContext();
}
public Object getListProperty() {
checkCurrentContext();
return null;
}
private void checkCurrentContext() {
assertEquals(expectedName, getCurrentSubjectName());
}
}
private static class NonPrivilegedSpringCallbacksBean implements
InitializingBean, DisposableBean, BeanClassLoaderAware,
BeanFactoryAware, BeanNameAware {
private String expectedName;
public static boolean destroyed = false;
public NonPrivilegedSpringCallbacksBean(String expected) {
this.expectedName = expected;
checkCurrentContext();
}
public void afterPropertiesSet() {
checkCurrentContext();
}
public void destroy() {
checkCurrentContext();
destroyed = true;
}
public void setBeanName(String name) {
checkCurrentContext();
}
public void setBeanClassLoader(ClassLoader classLoader) {
checkCurrentContext();
}
public void setBeanFactory(BeanFactory beanFactory)
throws BeansException {
checkCurrentContext();
}
private void checkCurrentContext() {
assertEquals(expectedName, getCurrentSubjectName());
}
}
private static class NonPrivilegedFactoryBean implements SmartFactoryBean {
private String expectedName;
public NonPrivilegedFactoryBean(String expected) {
this.expectedName = expected;
checkCurrentContext();
}
public boolean isEagerInit() {
checkCurrentContext();
return false;
}
public boolean isPrototype() {
checkCurrentContext();
return true;
}
public Object getObject() throws Exception {
checkCurrentContext();
return new Object();
}
public Class getObjectType() {
checkCurrentContext();
return Object.class;
}
public boolean isSingleton() {
checkCurrentContext();
return false;
}
private void checkCurrentContext() {
assertEquals(expectedName, getCurrentSubjectName());
}
}
private static class NonPrivilegedFactory {
private final String expectedName;
public NonPrivilegedFactory(String expected) {
this.expectedName = expected;
assertEquals(expectedName, getCurrentSubjectName());
}
public static Object makeStaticInstance(String expectedName) {
assertEquals(expectedName, getCurrentSubjectName());
return new Object();
}
public Object makeInstance() {
assertEquals(expectedName, getCurrentSubjectName());
return new Object();
}
}
private static String getCurrentSubjectName() {
final AccessControlContext acc = AccessController.getContext();
return AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
Subject subject = Subject.getSubject(acc);
if (subject == null) {
return null;
}
Set<Principal> principals = subject.getPrincipals();
if (principals == null) {
return null;
}
for (Principal p : principals) {
return p.getName();
}
return null;
}
});
}
private static class TestPrincipal implements Principal {
private String name;
public TestPrincipal(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TestPrincipal)) {
return false;
}
TestPrincipal p = (TestPrincipal) obj;
return this.name.equals(p.name);
}
public int hashCode() {
return this.name.hashCode();
}
}
public CallbacksSecurityTests() {
// setup security
if (System.getSecurityManager() == null) {
Policy policy = Policy.getPolicy();
URL policyURL = getClass()
.getResource(
"/org/springframework/beans/factory/support/security/policy.all");
System.setProperty("java.security.policy", policyURL.toString());
System.setProperty("policy.allowSystemProperty", "true");
policy.refresh();
System.setSecurityManager(new SecurityManager());
}
}
@Before
public void setUp() throws Exception {
final ProtectionDomain empty = new ProtectionDomain(null,
new Permissions());
provider = new SecurityContextProvider() {
private final AccessControlContext acc = new AccessControlContext(
new ProtectionDomain[] { empty });
public AccessControlContext getAccessControlContext() {
return acc;
}
};
DefaultResourceLoader drl = new DefaultResourceLoader();
Resource config = drl
.getResource("/org/springframework/beans/factory/support/security/callbacks.xml");
beanFactory = new XmlBeanFactory(config);
beanFactory.setSecurityContextProvider(provider);
}
@Test
public void testSecuritySanity() throws Exception {
AccessControlContext acc = provider.getAccessControlContext();
try {
acc.checkPermission(new PropertyPermission("*", "read"));
fail("Acc should not have any permissions");
} catch (SecurityException se) {
// expected
}
final CustomCallbackBean bean = new CustomCallbackBean();
final Method method = bean.getClass().getMethod("destroy", null);
method.setAccessible(true);
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
method.invoke(bean, null);
return null;
}
}, acc);
fail("expected security exception");
} catch (Exception ex) {
}
final Class<ConstructorBean> cl = ConstructorBean.class;
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return cl.newInstance();
}
}, acc);
fail("expected security exception");
} catch (Exception ex) {
}
}
@Test
public void testSpringInitBean() throws Exception {
try {
beanFactory.getBean("spring-init");
fail("expected security exception");
} catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException);
}
}
@Test
public void testCustomInitBean() throws Exception {
try {
beanFactory.getBean("custom-init");
fail("expected security exception");
} catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException);
}
}
@Test
public void testSpringDestroyBean() throws Exception {
beanFactory.getBean("spring-destroy");
beanFactory.destroySingletons();
assertNull(System.getProperty("security.destroy"));
}
@Test
public void testCustomDestroyBean() throws Exception {
beanFactory.getBean("custom-destroy");
beanFactory.destroySingletons();
assertNull(System.getProperty("security.destroy"));
}
@Test
public void testCustomFactoryObject() throws Exception {
try {
beanFactory.getBean("spring-factory");
fail("expected security exception");
} catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException);
}
}
@Test
public void testCustomFactoryType() throws Exception {
assertNull(beanFactory.getType("spring-factory"));
assertNull(System.getProperty("factory.object.type"));
}
@Test
public void testCustomStaticFactoryMethod() throws Exception {
try {
beanFactory.getBean("custom-static-factory-method");
fail("expected security exception");
} catch (BeanCreationException ex) {
assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
}
}
@Test
public void testCustomInstanceFactoryMethod() throws Exception {
try {
beanFactory.getBean("custom-factory-method");
fail("expected security exception");
} catch (BeanCreationException ex) {
assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
}
}
@Test
public void testTrustedFactoryMethod() throws Exception {
try {
beanFactory.getBean("privileged-static-factory-method");
fail("expected security exception");
} catch (BeanCreationException ex) {
assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
}
}
@Test
public void testConstructor() throws Exception {
try {
beanFactory.getBean("constructor");
fail("expected security exception");
} catch (BeanCreationException ex) {
// expected
assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
}
}
@Test
public void testContainerPriviledges() throws Exception {
AccessControlContext acc = provider.getAccessControlContext();
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
beanFactory.getBean("working-factory-method");
beanFactory.getBean("container-execution");
return null;
}
}, acc);
}
@Test
public void testPropertyInjection() throws Exception {
try {
beanFactory.getBean("property-injection");
fail("expected security exception");
} catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("security"));
}
beanFactory.getBean("working-property-injection");
}
@Test
public void testInitSecurityAwarePrototypeBean() {
final DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
BeanDefinitionBuilder bdb = BeanDefinitionBuilder
.genericBeanDefinition(NonPrivilegedBean.class).setScope(
ConfigurableBeanFactory.SCOPE_PROTOTYPE)
.setInitMethodName("init").setDestroyMethodName("destroy")
.addConstructorArgValue("user1");
lbf.registerBeanDefinition("test", bdb.getBeanDefinition());
final Subject subject = new Subject();
subject.getPrincipals().add(new TestPrincipal("user1"));
NonPrivilegedBean bean = Subject.doAsPrivileged(
subject, new PrivilegedAction<NonPrivilegedBean>() {
public NonPrivilegedBean run() {
return lbf.getBean("test", NonPrivilegedBean.class);
}
}, null);
assertNotNull(bean);
}
@Test
public void testTrustedExecution() throws Exception {
beanFactory.setSecurityContextProvider(null);
Permissions perms = new Permissions();
perms.add(new AuthPermission("getSubject"));
ProtectionDomain pd = new ProtectionDomain(null, perms);
AccessControlContext acc = new AccessControlContext(
new ProtectionDomain[] { pd });
final Subject subject = new Subject();
subject.getPrincipals().add(new TestPrincipal("user1"));
// request the beans from non-privileged code
Subject.doAsPrivileged(subject, new PrivilegedAction<Object>() {
public Object run() {
// sanity check
assertEquals("user1", getCurrentSubjectName());
assertEquals(false, NonPrivilegedBean.destroyed);
beanFactory.getBean("trusted-spring-callbacks");
beanFactory.getBean("trusted-custom-init-destroy");
// the factory is a prototype - ask for multiple instances
beanFactory.getBean("trusted-spring-factory");
beanFactory.getBean("trusted-spring-factory");
beanFactory.getBean("trusted-spring-factory");
beanFactory.getBean("trusted-factory-bean");
beanFactory.getBean("trusted-static-factory-method");
beanFactory.getBean("trusted-factory-method");
beanFactory.getBean("trusted-property-injection");
beanFactory.getBean("trusted-working-property-injection");
beanFactory.destroySingletons();
assertEquals(true, NonPrivilegedBean.destroyed);
return null;
}
}, provider.getAccessControlContext());
}
}

View File

@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="true">
<bean name="spring-init" class="org.springframework.beans.factory.support.security.support.InitBean"/>
<bean name="spring-destroy" class="org.springframework.beans.factory.support.security.support.DestroyBean"/>
<bean name="custom-init" class="org.springframework.beans.factory.support.security.support.CustomCallbackBean"
init-method="init"/>
<bean name="custom-destroy" class="org.springframework.beans.factory.support.security.support.CustomCallbackBean"
destroy-method="destroy"/>
<bean name="spring-factory" class="org.springframework.beans.factory.support.security.support.CustomFactoryBean"/>
<bean name="custom-static-factory-method" class="org.springframework.beans.factory.support.security.support.FactoryBean" factory-method="makeStaticInstance"/>
<bean name="factory-bean" class="org.springframework.beans.factory.support.security.support.FactoryBean"/>
<bean name="custom-factory-method" factory-bean="factory-bean" factory-method="makeInstance"/>
<bean name="constructor" class="org.springframework.beans.factory.support.security.support.ConstructorBean"/>
<bean name="working-factory-method" class="org.springframework.beans.factory.support.security.support.FactoryBean" factory-method="protectedStaticInstance"/>
<bean name="container-execution" class="org.springframework.beans.factory.support.security.support.ConstructorBean">
<constructor-arg ref="working-factory-method"/>
</bean>
<bean name="property-injection" class="org.springframework.beans.factory.support.security.support.PropertyBean">
<property name="securityProperty" value="value"/>
</bean>
<bean name="working-property-injection" class="org.springframework.beans.factory.support.security.support.PropertyBean">
<property name="property">
<array>
<ref bean="working-factory-method"/>
</array>
</property>
</bean>
<bean name="privileged-static-factory-method" class="java.lang.System" factory-method="getProperties"/>
<!-- check trusted beans -->
<bean name="trusted-spring-callbacks" class="org.springframework.beans.factory.support.security.CallbacksSecurityTests$NonPrivilegedSpringCallbacksBean">
<constructor-arg value="user1"/>
</bean>
<bean name="trusted-custom-init-destroy" class="org.springframework.beans.factory.support.security.CallbacksSecurityTests$NonPrivilegedBean"
init-method="init" destroy-method="destroy">
<constructor-arg value="user1"/>
</bean>
<bean name="trusted-spring-factory" class="org.springframework.beans.factory.support.security.CallbacksSecurityTests$NonPrivilegedFactoryBean">
<constructor-arg value="user1"/>
</bean>
<bean name="trusted-static-factory-method" class="org.springframework.beans.factory.support.security.CallbacksSecurityTests$NonPrivilegedFactory"
factory-method="makeStaticInstance">
<constructor-arg value="user1"/>
</bean>
<bean name="trusted-factory-bean" class="org.springframework.beans.factory.support.security.CallbacksSecurityTests$NonPrivilegedFactory">
<constructor-arg value="user1"/>
</bean>
<bean name="trusted-factory-method" factory-bean="trusted-factory-bean" factory-method="makeInstance"/>
<bean name="trusted-property-injection" class="org.springframework.beans.factory.support.security.CallbacksSecurityTests$NonPrivilegedBean">
<constructor-arg value="user1"/>
<property name="property" value="value"/>
</bean>
<bean name="trusted-working-property-injection" class="org.springframework.beans.factory.support.security.CallbacksSecurityTests$NonPrivilegedBean">
<constructor-arg value="user1"/>
<property name="property">
<map>
<entry key-ref="trusted-property-injection" value-ref="trusted-factory-method"/>
</map>
</property>
<property name="listProperty">
<list>
<value>foo</value>
<value>bar</value>
</list>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,3 @@
grant {
permission java.security.AllPermission;
};

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2006-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.beans.factory.support.security.support;
/**
* @author Costin Leau
*/
public class ConstructorBean {
public ConstructorBean() {
System.getProperties();
}
public ConstructorBean(Object obj) {
System.out.println("Received object " + obj);
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2006-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.beans.factory.support.security.support;
/**
* @author Costin Leau
*/
public class CustomCallbackBean {
public void init() {
System.getProperties();
}
public void destroy() {
System.setProperty("security.destroy", "true");
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2006-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.beans.factory.support.security.support;
import java.util.Properties;
import org.springframework.beans.factory.FactoryBean;
/**
* @author Costin Leau
*/
public class CustomFactoryBean implements FactoryBean<Object> {
public Object getObject() throws Exception {
return System.getProperties();
}
public Class getObjectType() {
System.setProperty("factory.object.type", "true");
return Properties.class;
}
public boolean isSingleton() {
return true;
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2006-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.beans.factory.support.security.support;
import org.springframework.beans.factory.DisposableBean;
/**
* @author Costin Leau
*/
public class DestroyBean implements DisposableBean {
public void destroy() throws Exception {
System.setProperty("security.destroy", "true");
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2006-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.beans.factory.support.security.support;
/**
* @author Costin Leau
*/
public class FactoryBean {
public static Object makeStaticInstance() {
System.getProperties();
return new Object();
}
protected static Object protectedStaticInstance() {
return "protectedStaticInstance";
}
public Object makeInstance() {
System.getProperties();
return new Object();
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2006-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.beans.factory.support.security.support;
import org.springframework.beans.factory.InitializingBean;
/**
* @author Costin Leau
*/
public class InitBean implements InitializingBean {
public void afterPropertiesSet() throws Exception {
System.getProperties();
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2006-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.beans.factory.support.security.support;
/**
* @author Costin Leau
*/
public class PropertyBean {
public void setSecurityProperty(Object property) {
System.getProperties();
}
public void setProperty(Object property) {
}
}

View File

@@ -0,0 +1,137 @@
/*
* Copyright 2002-2008 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.beans.factory.wiring;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import test.beans.TestBean;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class BeanConfigurerSupportTests extends TestCase {
public void testSupplyIncompatibleBeanFactoryImplementation() throws Exception {
MockControl mock = MockControl.createControl(BeanFactory.class);
mock.replay();
try {
new StubBeanConfigurerSupport().setBeanFactory((BeanFactory) mock.getMock());
fail("Must have thrown an IllegalArgumentException by this point (incompatible BeanFactory implementation supplied)");
}
catch (IllegalArgumentException expected) {
}
mock.verify();
}
public void testConfigureBeanDoesNothingIfBeanWiringInfoResolverResolvesToNull() throws Exception {
TestBean beanInstance = new TestBean();
MockControl mock = MockControl.createControl(BeanWiringInfoResolver.class);
BeanWiringInfoResolver resolver = (BeanWiringInfoResolver) mock.getMock();
resolver.resolveWiringInfo(beanInstance);
mock.setReturnValue(null);
mock.replay();
BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
configurer.setBeanWiringInfoResolver(resolver);
configurer.setBeanFactory(new DefaultListableBeanFactory());
configurer.configureBean(beanInstance);
mock.verify();
assertNull(beanInstance.getName());
}
public void testConfigureBeanDoesNothingIfNoBeanFactoryHasBeenSet() throws Exception {
TestBean beanInstance = new TestBean();
BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
configurer.configureBean(beanInstance);
assertNull(beanInstance.getName());
}
public void testConfigureBeanReallyDoesDefaultToUsingTheFullyQualifiedClassNameOfTheSuppliedBeanInstance() throws Exception {
TestBean beanInstance = new TestBean();
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
builder.addPropertyValue("name", "Harriet Wheeler");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition(beanInstance.getClass().getName(), builder.getBeanDefinition());
BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
configurer.setBeanFactory(factory);
configurer.afterPropertiesSet();
configurer.configureBean(beanInstance);
assertEquals("Bean is evidently not being configured (for some reason)", "Harriet Wheeler", beanInstance.getName());
}
public void testConfigureBeanPerformsAutowiringByNameIfAppropriateBeanWiringInfoResolverIsPluggedIn() throws Exception {
TestBean beanInstance = new TestBean();
// spouse for autowiring by name...
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
builder.addConstructorArgValue("David Gavurin");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("spouse", builder.getBeanDefinition());
MockControl mock = MockControl.createControl(BeanWiringInfoResolver.class);
BeanWiringInfoResolver resolver = (BeanWiringInfoResolver) mock.getMock();
resolver.resolveWiringInfo(beanInstance);
mock.setReturnValue(new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, false));
mock.replay();
BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
configurer.setBeanFactory(factory);
configurer.setBeanWiringInfoResolver(resolver);
configurer.configureBean(beanInstance);
assertEquals("Bean is evidently not being configured (for some reason)", "David Gavurin", beanInstance.getSpouse().getName());
mock.verify();
}
public void testConfigureBeanPerformsAutowiringByTypeIfAppropriateBeanWiringInfoResolverIsPluggedIn() throws Exception {
TestBean beanInstance = new TestBean();
// spouse for autowiring by type...
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
builder.addConstructorArgValue("David Gavurin");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("Mmm, I fancy a salad!", builder.getBeanDefinition());
MockControl mock = MockControl.createControl(BeanWiringInfoResolver.class);
BeanWiringInfoResolver resolver = (BeanWiringInfoResolver) mock.getMock();
resolver.resolveWiringInfo(beanInstance);
mock.setReturnValue(new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_TYPE, false));
mock.replay();
BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
configurer.setBeanFactory(factory);
configurer.setBeanWiringInfoResolver(resolver);
configurer.configureBean(beanInstance);
assertEquals("Bean is evidently not being configured (for some reason)", "David Gavurin", beanInstance.getSpouse().getName());
mock.verify();
}
private static class StubBeanConfigurerSupport extends BeanConfigurerSupport {
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright 2002-2006 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.beans.factory.wiring;
import junit.framework.TestCase;
/**
* Unit tests for the BeanWiringInfo class.
*
* @author Rick Evans
*/
public final class BeanWiringInfoTests extends TestCase {
public void testCtorWithNullBeanName() throws Exception {
try {
new BeanWiringInfo(null);
fail("Must have thrown an IllegalArgumentException by this point (null argument).");
}
catch (IllegalArgumentException ex) {
}
}
public void testCtorWithWhitespacedBeanName() throws Exception {
try {
new BeanWiringInfo(" \t");
fail("Must have thrown an IllegalArgumentException by this point (bean name has only whitespace).");
}
catch (IllegalArgumentException ex) {
}
}
public void testCtorWithEmptyBeanName() throws Exception {
try {
new BeanWiringInfo("");
fail("Must have thrown an IllegalArgumentException by this point (bean name is empty).");
}
catch (IllegalArgumentException ex) {
}
}
public void testCtorWithNegativeIllegalAutowiringValue() throws Exception {
try {
new BeanWiringInfo(-1, true);
fail("Must have thrown an IllegalArgumentException by this point (out-of-range argument).");
}
catch (IllegalArgumentException ex) {
}
}
public void testCtorWithPositiveOutOfRangeAutowiringValue() throws Exception {
try {
new BeanWiringInfo(123871, true);
fail("Must have thrown an IllegalArgumentException by this point (out-of-range argument).");
}
catch (IllegalArgumentException ex) {
}
}
public void testUsingAutowireCtorIndicatesAutowiring() throws Exception {
BeanWiringInfo info = new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, true);
assertTrue(info.indicatesAutowiring());
}
public void testUsingBeanNameCtorDoesNotIndicateAutowiring() throws Exception {
BeanWiringInfo info = new BeanWiringInfo("fooService");
assertFalse(info.indicatesAutowiring());
}
public void testNoDependencyCheckValueIsPreserved() throws Exception {
BeanWiringInfo info = new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, true);
assertTrue(info.getDependencyCheck());
}
public void testDependencyCheckValueIsPreserved() throws Exception {
BeanWiringInfo info = new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_TYPE, false);
assertFalse(info.getDependencyCheck());
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2006 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.beans.factory.wiring;
import junit.framework.TestCase;
/**
* Unit tests for the ClassNameBeanWiringInfoResolver class.
*
* @author Rick Evans
*/
public final class ClassNameBeanWiringInfoResolverTests extends TestCase {
public void testResolveWiringInfoWithNullBeanInstance() throws Exception {
try {
new ClassNameBeanWiringInfoResolver().resolveWiringInfo(null);
fail("Must have thrown an IllegalArgumentException by this point (null argument).");
}
catch (IllegalArgumentException expected) {
}
}
public void testResolveWiringInfo() {
ClassNameBeanWiringInfoResolver resolver = new ClassNameBeanWiringInfoResolver();
Long beanInstance = new Long(1);
BeanWiringInfo info = resolver.resolveWiringInfo(beanInstance);
assertNotNull(info);
assertEquals("Not resolving bean name to the class name of the supplied bean instance as per class contract.",
beanInstance.getClass().getName(), info.getBeanName());
}
}

View File

@@ -0,0 +1,366 @@
/*
* Copyright 2002-2008 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.beans.factory.xml;
import java.beans.PropertyEditorSupport;
import java.util.StringTokenizer;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyBatchUpdateException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanIsNotAFactoryException;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import test.beans.DummyFactory;
import test.beans.LifecycleBean;
import test.beans.TestBean;
/**
* Subclasses must implement setUp() to initialize bean factory
* and any other variables they need.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractBeanFactoryTests extends TestCase {
protected abstract BeanFactory getBeanFactory();
/**
* Roderick beans inherits from rod, overriding name only.
*/
public void testInheritance() {
assertTrue(getBeanFactory().containsBean("rod"));
assertTrue(getBeanFactory().containsBean("roderick"));
TestBean rod = (TestBean) getBeanFactory().getBean("rod");
TestBean roderick = (TestBean) getBeanFactory().getBean("roderick");
assertTrue("not == ", rod != roderick);
assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
assertTrue("rod.age is 31", rod.getAge() == 31);
assertTrue("roderick.name is Roderick", roderick.getName().equals("Roderick"));
assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge());
}
public void testGetBeanWithNullArg() {
try {
getBeanFactory().getBean((String) null);
fail("Can't get null bean");
}
catch (IllegalArgumentException ex) {
// OK
}
}
/**
* Test that InitializingBean objects receive the afterPropertiesSet() callback
*/
public void testInitializingBeanCallback() {
MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized");
// The dummy business method will throw an exception if the
// afterPropertiesSet() callback wasn't invoked
mbi.businessMethod();
}
/**
* Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the
* afterPropertiesSet() callback before BeanFactoryAware callbacks
*/
public void testLifecycleCallbacks() {
LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle");
Assert.assertEquals("lifecycle", lb.getBeanName());
// The dummy business method will throw an exception if the
// necessary callbacks weren't invoked in the right order.
lb.businessMethod();
assertTrue("Not destroyed", !lb.isDestroyed());
}
public void testFindsValidInstance() {
try {
Object o = getBeanFactory().getBean("rod");
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
TestBean rod = (TestBean) o;
assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
assertTrue("rod.age is 31", rod.getAge() == 31);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testGetInstanceByMatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", TestBean.class);
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance with matching class");
}
}
public void testGetInstanceByNonmatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
}
catch (BeanNotOfRequiredTypeException ex) {
// So far, so good
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testGetSharedInstanceByMatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", TestBean.class);
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance with matching class");
}
}
public void testGetSharedInstanceByMatchingClassNoCatch() {
Object o = getBeanFactory().getBean("rod", TestBean.class);
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
}
public void testGetSharedInstanceByNonmatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
}
catch (BeanNotOfRequiredTypeException ex) {
// So far, so good
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testSharedInstancesAreEqual() {
try {
Object o = getBeanFactory().getBean("rod");
assertTrue("Rod bean1 is a TestBean", o instanceof TestBean);
Object o1 = getBeanFactory().getBean("rod");
assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean);
assertTrue("Object equals applies", o == o1);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testPrototypeInstancesAreIndependent() {
TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy");
TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy");
assertTrue("ref equal DOES NOT apply", tb1 != tb2);
assertTrue("object equal true", tb1.equals(tb2));
tb1.setAge(1);
tb2.setAge(2);
assertTrue("1 age independent = 1", tb1.getAge() == 1);
assertTrue("2 age independent = 2", tb2.getAge() == 2);
assertTrue("object equal now false", !tb1.equals(tb2));
}
public void testNotThere() {
assertFalse(getBeanFactory().containsBean("Mr Squiggle"));
try {
Object o = getBeanFactory().getBean("Mr Squiggle");
fail("Can't find missing bean");
}
catch (BeansException ex) {
//ex.printStackTrace();
//fail("Shouldn't throw exception on getting valid instance");
}
}
public void testValidEmpty() {
try {
Object o = getBeanFactory().getBean("validEmpty");
assertTrue("validEmpty bean is a TestBean", o instanceof TestBean);
TestBean ve = (TestBean) o;
assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null);
}
catch (BeansException ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on valid empty");
}
}
public void xtestTypeMismatch() {
try {
Object o = getBeanFactory().getBean("typeMismatch");
fail("Shouldn't succeed with type mismatch");
}
catch (BeanCreationException wex) {
assertEquals("typeMismatch", wex.getBeanName());
assertTrue(wex.getCause() instanceof PropertyBatchUpdateException);
PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause();
// Further tests
assertTrue("Has one error ", ex.getExceptionCount() == 1);
assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null);
assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x"));
}
}
public void testGrandparentDefinitionFoundInBeanFactory() throws Exception {
TestBean dad = (TestBean) getBeanFactory().getBean("father");
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
}
public void testFactorySingleton() throws Exception {
assertTrue(getBeanFactory().isSingleton("&singletonFactory"));
assertTrue(getBeanFactory().isSingleton("singletonFactory"));
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME));
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory");
assertTrue("Singleton references ==", tb == tb2);
assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null);
}
public void testFactoryPrototype() throws Exception {
assertTrue(getBeanFactory().isSingleton("&prototypeFactory"));
assertFalse(getBeanFactory().isSingleton("prototypeFactory"));
TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory");
assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME));
TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory");
assertTrue("Prototype references !=", tb != tb2);
}
/**
* Check that we can get the factory bean itself.
* This is only possible if we're dealing with a factory
* @throws Exception
*/
public void testGetFactoryItself() throws Exception {
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
assertTrue(factory != null);
}
/**
* Check that afterPropertiesSet gets called on factory
* @throws Exception
*/
public void testFactoryIsInitialized() throws Exception {
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized());
}
/**
* It should be illegal to dereference a normal bean
* as a factory
*/
public void testRejectsFactoryGetOnNormalBean() {
try {
getBeanFactory().getBean("&rod");
fail("Shouldn't permit factory get on normal bean");
}
catch (BeanIsNotAFactoryException ex) {
// Ok
}
}
// TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory)
// and rename this class
public void testAliasing() {
BeanFactory bf = getBeanFactory();
if (!(bf instanceof ConfigurableBeanFactory)) {
return;
}
ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf;
String alias = "rods alias";
try {
cbf.getBean(alias);
fail("Shouldn't permit factory get on normal bean");
}
catch (NoSuchBeanDefinitionException ex) {
// Ok
assertTrue(alias.equals(ex.getBeanName()));
}
// Create alias
cbf.registerAlias("rod", alias);
Object rod = getBeanFactory().getBean("rod");
Object aliasRod = getBeanFactory().getBean(alias);
assertTrue(rod == aliasRod);
}
public static class TestBeanEditor extends PropertyEditorSupport {
public void setAsText(String text) {
TestBean tb = new TestBean();
StringTokenizer st = new StringTokenizer(text, "_");
tb.setName(st.nextToken());
tb.setAge(Integer.parseInt(st.nextToken()));
setValue(tb);
}
}
}
/**
* Simple test of BeanFactory initialization
* @author Rod Johnson
* @since 12.03.2003
*/
class MustBeInitialized implements InitializingBean {
private boolean inited;
/**
* @see InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
this.inited = true;
}
/**
* Dummy business method that will fail unless the factory
* managed the bean's lifecycle correctly
*/
public void businessMethod() {
if (!this.inited)
throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object");
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2002-2007 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.beans.factory.xml;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.ListableBeanFactory;
import junit.framework.Assert;
import test.beans.TestBean;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFactoryTests {
/** Subclasses must initialize this */
protected ListableBeanFactory getListableBeanFactory() {
BeanFactory bf = getBeanFactory();
if (!(bf instanceof ListableBeanFactory)) {
throw new IllegalStateException("ListableBeanFactory required");
}
return (ListableBeanFactory) bf;
}
/**
* Subclasses can override this.
*/
public void testCount() {
assertCount(13);
}
protected final void assertCount(int count) {
String[] defnames = getListableBeanFactory().getBeanDefinitionNames();
Assert.assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count);
}
public void assertTestBeanCount(int count) {
String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false);
Assert.assertTrue("We should have " + count + " beans for class org.springframework.beans.TestBean, not " +
defNames.length, defNames.length == count);
int countIncludingFactoryBeans = count + 2;
String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true);
Assert.assertTrue("We should have " + countIncludingFactoryBeans +
" beans for class org.springframework.beans.TestBean, not " + names.length,
names.length == countIncludingFactoryBeans);
}
public void testGetDefinitionsForNoSuchClass() {
String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class);
Assert.assertTrue("No string definitions", defnames.length == 0);
}
/**
* Check that count refers to factory class, not bean class. (We don't know
* what type factories may return, and it may even change over time.)
*/
public void testGetCountForFactoryClass() {
Assert.assertTrue("Should have 2 factories, not " +
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
Assert.assertTrue("Should have 2 factories, not " +
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
}
public void testContainsBeanDefinition() {
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("rod"));
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("roderick"));
}
}

View File

@@ -0,0 +1,159 @@
/*
* 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.beans.factory.xml;
import junit.framework.Assert;
import junit.framework.TestCase;
import test.beans.TestBean;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.io.ClassPathResource;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class AutowireWithExclusionTests extends TestCase {
public void testByTypeAutowireWithAutoSelfExclusion() throws Exception {
CountingFactory.reset();
XmlBeanFactory beanFactory = getBeanFactory("autowire-with-exclusion.xml");
beanFactory.preInstantiateSingletons();
TestBean rob = (TestBean) beanFactory.getBean("rob");
TestBean sally = (TestBean) beanFactory.getBean("sally");
assertEquals(sally, rob.getSpouse());
Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
public void testByTypeAutowireWithExclusion() throws Exception {
CountingFactory.reset();
XmlBeanFactory beanFactory = getBeanFactory("autowire-with-exclusion.xml");
beanFactory.preInstantiateSingletons();
TestBean rob = (TestBean) beanFactory.getBean("rob");
assertEquals("props1", rob.getSomeProperties().getProperty("name"));
Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
public void testByTypeAutowireWithExclusionInParentFactory() throws Exception {
CountingFactory.reset();
XmlBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
parent.preInstantiateSingletons();
DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE);
robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally"));
child.registerBeanDefinition("rob2", robDef);
TestBean rob = (TestBean) child.getBean("rob2");
assertEquals("props1", rob.getSomeProperties().getProperty("name"));
Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
public void testByTypeAutowireWithPrimaryInParentFactory() throws Exception {
CountingFactory.reset();
XmlBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
parent.getBeanDefinition("props1").setPrimary(true);
parent.preInstantiateSingletons();
DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE);
robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally"));
child.registerBeanDefinition("rob2", robDef);
RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class);
propsDef.getPropertyValues().add("properties", "name=props3");
child.registerBeanDefinition("props3", propsDef);
TestBean rob = (TestBean) child.getBean("rob2");
assertEquals("props1", rob.getSomeProperties().getProperty("name"));
Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
public void testByTypeAutowireWithPrimaryOverridingParentFactory() throws Exception {
CountingFactory.reset();
XmlBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
parent.preInstantiateSingletons();
DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE);
robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally"));
child.registerBeanDefinition("rob2", robDef);
RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class);
propsDef.getPropertyValues().add("properties", "name=props3");
propsDef.setPrimary(true);
child.registerBeanDefinition("props3", propsDef);
TestBean rob = (TestBean) child.getBean("rob2");
assertEquals("props3", rob.getSomeProperties().getProperty("name"));
Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
public void testByTypeAutowireWithPrimaryInParentAndChild() throws Exception {
CountingFactory.reset();
XmlBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
parent.getBeanDefinition("props1").setPrimary(true);
parent.preInstantiateSingletons();
DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE);
robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally"));
child.registerBeanDefinition("rob2", robDef);
RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class);
propsDef.getPropertyValues().add("properties", "name=props3");
propsDef.setPrimary(true);
child.registerBeanDefinition("props3", propsDef);
TestBean rob = (TestBean) child.getBean("rob2");
assertEquals("props3", rob.getSomeProperties().getProperty("name"));
Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
public void testByTypeAutowireWithInclusion() throws Exception {
CountingFactory.reset();
XmlBeanFactory beanFactory = getBeanFactory("autowire-with-inclusion.xml");
beanFactory.preInstantiateSingletons();
TestBean rob = (TestBean) beanFactory.getBean("rob");
assertEquals("props1", rob.getSomeProperties().getProperty("name"));
Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
public void testByTypeAutowireWithSelectiveInclusion() throws Exception {
CountingFactory.reset();
XmlBeanFactory beanFactory = getBeanFactory("autowire-with-selective-inclusion.xml");
beanFactory.preInstantiateSingletons();
TestBean rob = (TestBean) beanFactory.getBean("rob");
assertEquals("props1", rob.getSomeProperties().getProperty("name"));
Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
public void testConstructorAutowireWithAutoSelfExclusion() throws Exception {
XmlBeanFactory beanFactory = getBeanFactory("autowire-constructor-with-exclusion.xml");
TestBean rob = (TestBean) beanFactory.getBean("rob");
TestBean sally = (TestBean) beanFactory.getBean("sally");
assertEquals(sally, rob.getSpouse());
TestBean rob2 = (TestBean) beanFactory.getBean("rob");
assertEquals(rob, rob2);
assertNotSame(rob, rob2);
assertEquals(rob.getSpouse(), rob2.getSpouse());
assertNotSame(rob.getSpouse(), rob2.getSpouse());
}
public void testConstructorAutowireWithExclusion() throws Exception {
XmlBeanFactory beanFactory = getBeanFactory("autowire-constructor-with-exclusion.xml");
TestBean rob = (TestBean) beanFactory.getBean("rob");
assertEquals("props1", rob.getSomeProperties().getProperty("name"));
}
private XmlBeanFactory getBeanFactory(String configPath) {
return new XmlBeanFactory(new ClassPathResource(configPath, getClass()));
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2007 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.beans.factory.xml;
import junit.framework.TestCase;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.ClassPathResource;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class BeanNameGenerationTests extends TestCase {
private DefaultListableBeanFactory beanFactory;
public void setUp() {
this.beanFactory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
reader.loadBeanDefinitions(new ClassPathResource("beanNameGeneration.xml", getClass()));
}
public void testNaming() {
String className = GeneratedNameBean.class.getName();
String targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "0";
GeneratedNameBean topLevel1 = (GeneratedNameBean) beanFactory.getBean(targetName);
assertNotNull(topLevel1);
targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "1";
GeneratedNameBean topLevel2 = (GeneratedNameBean) beanFactory.getBean(targetName);
assertNotNull(topLevel2);
GeneratedNameBean child1 = topLevel1.getChild();
assertNotNull(child1.getBeanName());
assertTrue(child1.getBeanName().startsWith(className));
GeneratedNameBean child2 = topLevel2.getChild();
assertNotNull(child2.getBeanName());
assertTrue(child2.getBeanName().startsWith(className));
assertFalse(child1.getBeanName().equals(child2.getBeanName()));
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2002-2007 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.beans.factory.xml;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.parsing.AliasDefinition;
import org.springframework.beans.factory.parsing.ComponentDefinition;
import org.springframework.beans.factory.parsing.DefaultsDefinition;
import org.springframework.beans.factory.parsing.ImportDefinition;
import org.springframework.beans.factory.parsing.ReaderEventListener;
import org.springframework.core.CollectionFactory;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class CollectingReaderEventListener implements ReaderEventListener {
private final List defaults = new LinkedList();
private final Map componentDefinitions = CollectionFactory.createLinkedMapIfPossible(8);
private final Map aliasMap = CollectionFactory.createLinkedMapIfPossible(8);
private final List imports = new LinkedList();
public void defaultsRegistered(DefaultsDefinition defaultsDefinition) {
this.defaults.add(defaultsDefinition);
}
public List getDefaults() {
return Collections.unmodifiableList(this.defaults);
}
public void componentRegistered(ComponentDefinition componentDefinition) {
this.componentDefinitions.put(componentDefinition.getName(), componentDefinition);
}
public ComponentDefinition getComponentDefinition(String name) {
return (ComponentDefinition) this.componentDefinitions.get(name);
}
public ComponentDefinition[] getComponentDefinitions() {
Collection collection = this.componentDefinitions.values();
return (ComponentDefinition[]) collection.toArray(new ComponentDefinition[collection.size()]);
}
public void aliasRegistered(AliasDefinition aliasDefinition) {
List aliases = (List) this.aliasMap.get(aliasDefinition.getBeanName());
if(aliases == null) {
aliases = new ArrayList();
this.aliasMap.put(aliasDefinition.getBeanName(), aliases);
}
aliases.add(aliasDefinition);
}
public List getAliases(String beanName) {
List aliases = (List) this.aliasMap.get(beanName);
return aliases == null ? null : Collections.unmodifiableList(aliases);
}
public void importProcessed(ImportDefinition importDefinition) {
this.imports.add(importDefinition);
}
public List getImports() {
return Collections.unmodifiableList(this.imports);
}
}

View File

@@ -0,0 +1,184 @@
/*
* Copyright 2002-2007 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.beans.factory.xml;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import junit.framework.TestCase;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.ClassPathResource;
import test.beans.TestBean;
/**
* Unit and integration tests for the collection merging support.
*
* @author Rob Harrop
* @author Rick Evans
*/
public class CollectionMergingTests extends TestCase {
private DefaultListableBeanFactory beanFactory;
protected void setUp() throws Exception {
this.beanFactory = new DefaultListableBeanFactory();
BeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
reader.loadBeanDefinitions(new ClassPathResource("collectionMerging.xml", getClass()));
}
public void testMergeList() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithList");
List list = bean.getSomeList();
assertEquals("Incorrect size", 3, list.size());
assertEquals(list.get(0), "Rob Harrop");
assertEquals(list.get(1), "Rod Johnson");
assertEquals(list.get(2), "Juergen Hoeller");
}
public void testMergeListWithInnerBeanAsListElement() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithListOfRefs");
List list = bean.getSomeList();
assertNotNull(list);
assertEquals(3, list.size());
assertNotNull(list.get(2));
assertTrue(list.get(2) instanceof TestBean);
}
public void testMergeSet() {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithSet");
Set set = bean.getSomeSet();
assertEquals("Incorrect size", 2, set.size());
assertTrue(set.contains("Rob Harrop"));
assertTrue(set.contains("Sally Greenwood"));
}
public void testMergeSetWithInnerBeanAsSetElement() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetOfRefs");
Set set = bean.getSomeSet();
assertNotNull(set);
assertEquals(2, set.size());
Iterator it = set.iterator();
it.next();
Object o = it.next();
assertNotNull(o);
assertTrue(o instanceof TestBean);
assertEquals("Sally", ((TestBean) o).getName());
}
public void testMergeMap() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithMap");
Map map = bean.getSomeMap();
assertEquals("Incorrect size", 3, map.size());
assertEquals(map.get("Rob"), "Sally");
assertEquals(map.get("Rod"), "Kerry");
assertEquals(map.get("Juergen"), "Eva");
}
public void testMergeMapWithInnerBeanAsMapEntryValue() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapOfRefs");
Map map = bean.getSomeMap();
assertNotNull(map);
assertEquals(2, map.size());
assertNotNull(map.get("Rob"));
assertTrue(map.get("Rob") instanceof TestBean);
assertEquals("Sally", ((TestBean) map.get("Rob")).getName());
}
public void testMergeProperties() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithProps");
Properties props = bean.getSomeProperties();
assertEquals("Incorrect size", 3, props.size());
assertEquals(props.getProperty("Rob"), "Sally");
assertEquals(props.getProperty("Rod"), "Kerry");
assertEquals(props.getProperty("Juergen"), "Eva");
}
public void testMergeListInConstructor() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithListInConstructor");
List list = bean.getSomeList();
assertEquals("Incorrect size", 3, list.size());
assertEquals(list.get(0), "Rob Harrop");
assertEquals(list.get(1), "Rod Johnson");
assertEquals(list.get(2), "Juergen Hoeller");
}
public void testMergeListWithInnerBeanAsListElementInConstructor() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithListOfRefsInConstructor");
List list = bean.getSomeList();
assertNotNull(list);
assertEquals(3, list.size());
assertNotNull(list.get(2));
assertTrue(list.get(2) instanceof TestBean);
}
public void testMergeSetInConstructor() {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetInConstructor");
Set set = bean.getSomeSet();
assertEquals("Incorrect size", 2, set.size());
assertTrue(set.contains("Rob Harrop"));
assertTrue(set.contains("Sally Greenwood"));
}
public void testMergeSetWithInnerBeanAsSetElementInConstructor() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetOfRefsInConstructor");
Set set = bean.getSomeSet();
assertNotNull(set);
assertEquals(2, set.size());
Iterator it = set.iterator();
it.next();
Object o = it.next();
assertNotNull(o);
assertTrue(o instanceof TestBean);
assertEquals("Sally", ((TestBean) o).getName());
}
public void testMergeMapInConstructor() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapInConstructor");
Map map = bean.getSomeMap();
assertEquals("Incorrect size", 3, map.size());
assertEquals(map.get("Rob"), "Sally");
assertEquals(map.get("Rod"), "Kerry");
assertEquals(map.get("Juergen"), "Eva");
}
public void testMergeMapWithInnerBeanAsMapEntryValueInConstructor() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapOfRefsInConstructor");
Map map = bean.getSomeMap();
assertNotNull(map);
assertEquals(2, map.size());
assertNotNull(map.get("Rob"));
assertTrue(map.get("Rob") instanceof TestBean);
assertEquals("Sally", ((TestBean) map.get("Rob")).getName());
}
public void testMergePropertiesInConstructor() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("childWithPropsInConstructor");
Properties props = bean.getSomeProperties();
assertEquals("Incorrect size", 3, props.size());
assertEquals(props.getProperty("Rob"), "Sally");
assertEquals(props.getProperty("Rod"), "Kerry");
assertEquals(props.getProperty("Juergen"), "Eva");
}
}

Some files were not shown because too many files have changed in this diff Show More