moving unit tests from .testsuite -> .context

This commit is contained in:
Chris Beams
2008-12-14 19:47:56 +00:00
parent 69d80518f3
commit 87de85ef19
57 changed files with 231 additions and 171 deletions

View File

@@ -0,0 +1,41 @@
package org.springframework.beans;
import java.io.InputStream;
import org.springframework.core.io.Resource;
/**
* @author Juergen Hoeller
* @since 01.04.2004
*/
public class ResourceTestBean {
private Resource resource;
private InputStream inputStream;
public ResourceTestBean() {
}
public ResourceTestBean(Resource resource, InputStream inputStream) {
this.resource = resource;
this.inputStream = inputStream;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public Resource getResource() {
return resource;
}
public InputStream getInputStream() {
return inputStream;
}
}

View File

@@ -0,0 +1,329 @@
/*
* 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 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.TestBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
/**
* 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(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);
}
}
}

View File

@@ -0,0 +1,86 @@
/*
* 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;
import junit.framework.Assert;
import org.springframework.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,172 @@
/*
* 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;
import org.springframework.beans.BeansException;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
/**
* Simple factory to allow testing of FactoryBean support in AbstractBeanFactory.
* Depending on whether its singleton property is set, it will return a singleton
* or a prototype instance.
*
* <p>Implements InitializingBean interface, so we can check that
* factories get this lifecycle callback if they want.
*
* @author Rod Johnson
* @since 10.03.2003
*/
public class DummyFactory
implements FactoryBean, BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
public static final String SINGLETON_NAME = "Factory singleton";
private static boolean prototypeCreated;
/**
* Clear static state.
*/
public static void reset() {
prototypeCreated = false;
}
/**
* Default is for factories to return a singleton instance.
*/
private boolean singleton = true;
private String beanName;
private AutowireCapableBeanFactory beanFactory;
private boolean postProcessed;
private boolean initialized;
private TestBean testBean;
private TestBean otherTestBean;
public DummyFactory() {
this.testBean = new TestBean();
this.testBean.setName(SINGLETON_NAME);
this.testBean.setAge(25);
}
/**
* Return if the bean managed by this factory is a singleton.
* @see org.springframework.beans.factory.FactoryBean#isSingleton()
*/
public boolean isSingleton() {
return this.singleton;
}
/**
* Set if the bean managed by this factory is a singleton.
*/
public void setSingleton(boolean singleton) {
this.singleton = singleton;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = (AutowireCapableBeanFactory) beanFactory;
this.beanFactory.applyBeanPostProcessorsBeforeInitialization(this.testBean, this.beanName);
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
public void setPostProcessed(boolean postProcessed) {
this.postProcessed = postProcessed;
}
public boolean isPostProcessed() {
return postProcessed;
}
public void setOtherTestBean(TestBean otherTestBean) {
this.otherTestBean = otherTestBean;
this.testBean.setSpouse(otherTestBean);
}
public TestBean getOtherTestBean() {
return otherTestBean;
}
public void afterPropertiesSet() {
if (initialized) {
throw new RuntimeException("Cannot call afterPropertiesSet twice on the one bean");
}
this.initialized = true;
}
/**
* Was this initialized by invocation of the
* afterPropertiesSet() method from the InitializingBean interface?
*/
public boolean wasInitialized() {
return initialized;
}
public static boolean wasPrototypeCreated() {
return prototypeCreated;
}
/**
* Return the managed object, supporting both singleton
* and prototype mode.
* @see org.springframework.beans.factory.FactoryBean#getObject()
*/
public Object getObject() throws BeansException {
if (isSingleton()) {
return this.testBean;
}
else {
TestBean prototype = new TestBean("prototype created at " + System.currentTimeMillis(), 11);
if (this.beanFactory != null) {
this.beanFactory.applyBeanPostProcessorsBeforeInitialization(prototype, this.beanName);
}
prototypeCreated = true;
return prototype;
}
}
public Class getObjectType() {
return TestBean.class;
}
public void destroy() {
if (this.testBean != null) {
this.testBean.setName(null);
}
}
}

View File

@@ -0,0 +1,158 @@
/*
* 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;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* Simple test of BeanFactory initialization and lifecycle callbacks.
*
* @author Rod Johnson
* @author Colin Sampaleanu
* @since 12.03.2003
*/
public class LifecycleBean implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
protected boolean initMethodDeclared = false;
protected String beanName;
protected BeanFactory owningFactory;
protected boolean postProcessedBeforeInit;
protected boolean inited;
protected boolean initedViaDeclaredInitMethod;
protected boolean postProcessedAfterInit;
protected boolean destroyed;
public void setInitMethodDeclared(boolean initMethodDeclared) {
this.initMethodDeclared = initMethodDeclared;
}
public boolean isInitMethodDeclared() {
return initMethodDeclared;
}
public void setBeanName(String name) {
this.beanName = name;
}
public String getBeanName() {
return beanName;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.owningFactory = beanFactory;
}
public void postProcessBeforeInit() {
if (this.inited || this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called postProcessBeforeInit after afterPropertiesSet");
}
if (this.postProcessedBeforeInit) {
throw new RuntimeException("Factory called postProcessBeforeInit twice");
}
this.postProcessedBeforeInit = true;
}
public void afterPropertiesSet() {
if (this.owningFactory == null) {
throw new RuntimeException("Factory didn't call setBeanFactory before afterPropertiesSet on lifecycle bean");
}
if (!this.postProcessedBeforeInit) {
throw new RuntimeException("Factory didn't call postProcessBeforeInit before afterPropertiesSet on lifecycle bean");
}
if (this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory initialized via declared init method before initializing via afterPropertiesSet");
}
if (this.inited) {
throw new RuntimeException("Factory called afterPropertiesSet twice");
}
this.inited = true;
}
public void declaredInitMethod() {
if (!this.inited) {
throw new RuntimeException("Factory didn't call afterPropertiesSet before declared init method");
}
if (this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called declared init method twice");
}
this.initedViaDeclaredInitMethod = true;
}
public void postProcessAfterInit() {
if (!this.inited) {
throw new RuntimeException("Factory called postProcessAfterInit before afterPropertiesSet");
}
if (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called postProcessAfterInit before calling declared init method");
}
if (this.postProcessedAfterInit) {
throw new RuntimeException("Factory called postProcessAfterInit twice");
}
this.postProcessedAfterInit = true;
}
/**
* Dummy business method that will fail unless the factory
* managed the bean's lifecycle correctly
*/
public void businessMethod() {
if (!this.inited || (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) ||
!this.postProcessedAfterInit) {
throw new RuntimeException("Factory didn't initialize lifecycle object correctly");
}
}
public void destroy() {
if (this.destroyed) {
throw new IllegalStateException("Already destroyed");
}
this.destroyed = true;
}
public boolean isDestroyed() {
return destroyed;
}
public static class PostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
if (bean instanceof LifecycleBean) {
((LifecycleBean) bean).postProcessBeforeInit();
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
if (bean instanceof LifecycleBean) {
((LifecycleBean) bean).postProcessAfterInit();
}
return bean;
}
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2005 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;
/**
* Simple test of BeanFactory initialization
* @author Rod Johnson
* @since 12.03.2003
*/
public class MustBeInitialized implements InitializingBean {
private boolean inited;
/**
* @see org.springframework.beans.factory.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,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<import resource="resourceImport.xml"/>
<bean id="resource2" class="org.springframework.beans.ResourceTestBean">
<constructor-arg index="0">
<value>classpath:org/springframework/beans/factory/xml/test.properties</value>
</constructor-arg>
<constructor-arg index="1">
<value>classpath:org/springframework/beans/factory/xml/test.properties</value>
</constructor-arg>
</bean>
</beans>

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="resource1" class="org.springframework.beans.ResourceTestBean">
<property name="resource">
<value>classpath:org/springframework/beans/factory/xml/test.properties</value>
</property>
<property name="inputStream">
<value>classpath:org/springframework/beans/factory/xml/test.properties</value>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,127 @@
<?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="validEmptyWithDescription" class="org.springframework.beans.TestBean">
<description>
I have no properties and I'm happy without them.
</description>
</bean>
<!--
Check automatic creation of alias, to allow for names that are illegal as XML ids.
-->
<bean id="aliased" class=" org.springframework.beans.TestBean " name="myalias">
<property name="name"><value>aliased</value></property>
</bean>
<alias name="aliased" alias="youralias"/>
<alias name="multiAliased" alias="alias3"/>
<bean id="multiAliased" class="org.springframework.beans.TestBean" name="alias1,alias2">
<property name="name"><value>aliased</value></property>
</bean>
<alias name="multiAliased" alias="alias4"/>
<bean class="org.springframework.beans.TestBean" name="aliasWithoutId1,aliasWithoutId2,aliasWithoutId3">
<property name="name"><value>aliased</value></property>
</bean>
<bean class="org.springframework.beans.TestBean">
<property name="name"><null/></property>
</bean>
<bean class="org.springframework.beans.factory.xml.DummyReferencer"/>
<bean class="org.springframework.beans.factory.xml.DummyReferencer"/>
<bean class="org.springframework.beans.factory.xml.DummyReferencer"/>
<bean id="rod" class="org.springframework.beans.TestBean">
<property name="name"><value><!-- a comment -->Rod</value></property>
<property name="age"><value>31</value></property>
<property name="spouse"><ref bean="father"/></property>
<property name="touchy"><value/></property>
</bean>
<bean id="roderick" parent="rod">
<property name="name"><value>Roderick<!-- a comment --></value></property>
<!-- Should inherit age -->
</bean>
<bean id="kerry" class="org.springframework.beans.TestBean">
<property name="name"><value>Ker<!-- a comment -->ry</value></property>
<property name="age"><value>34</value></property>
<property name="spouse"><ref local="rod"/></property>
<property name="touchy"><value></value></property>
</bean>
<bean id="kathy" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name"><value>Kathy</value></property>
<property name="age"><value>28</value></property>
<property name="spouse"><ref bean="father"/></property>
</bean>
<bean id="typeMismatch" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name"><value>typeMismatch</value></property>
<property name="age"><value>34x</value></property>
<property name="spouse"><ref local="rod"/></property>
</bean>
<!-- Test of lifecycle callbacks -->
<bean id="mustBeInitialized" class="org.springframework.beans.factory.MustBeInitialized"/>
<bean id="lifecycle" class="org.springframework.beans.factory.LifecycleBean"
init-method="declaredInitMethod">
<property name="initMethodDeclared"><value>true</value></property>
</bean>
<bean id="protectedLifecycle" class="org.springframework.beans.factory.xml.ProtectedLifecycleBean"
init-method="declaredInitMethod">
<property name="initMethodDeclared"><value>true</value></property>
</bean>
<!-- Factory beans are automatically treated differently -->
<bean id="singletonFactory" class="org.springframework.beans.factory.DummyFactory">
</bean>
<bean id="prototypeFactory" class="org.springframework.beans.factory.DummyFactory">
<property name="singleton"><value>false</value></property>
</bean>
<!-- Check that the circular reference resolution mechanism doesn't break
repeated references to the same FactoryBean -->
<bean id="factoryReferencer" class="org.springframework.beans.factory.xml.DummyReferencer">
<property name="testBean1"><ref bean="singletonFactory"/></property>
<property name="testBean2"><ref local="singletonFactory"/></property>
<property name="dummyFactory"><ref bean="&amp;singletonFactory"/></property>
</bean>
<bean id="factoryReferencerWithConstructor" class="org.springframework.beans.factory.xml.DummyReferencer">
<constructor-arg><ref bean="&amp;singletonFactory"/></constructor-arg>
<property name="testBean1"><ref bean="singletonFactory"/></property>
<property name="testBean2"><ref local="singletonFactory"/></property>
</bean>
<!-- Check that the circular reference resolution mechanism doesn't break
prototype instantiation -->
<bean id="prototypeReferencer" class="org.springframework.beans.factory.xml.DummyReferencer" scope="prototype">
<property name="testBean1"><ref local="kathy"/></property>
<property name="testBean2"><ref bean="kathy"/></property>
</bean>
<bean id="listenerVeto" class="org.springframework.beans.TestBean">
<property name="name"><value>listenerVeto</value></property>
<property name="age"><value>66</value></property>
</bean>
<bean id="validEmpty" class="org.springframework.beans.TestBean"/>
<bean id="commentsInValue" class="org.springframework.beans.TestBean">
<property name="name"><value>this is<!-- don't mind me --> a <![CDATA[<!--comment-->]]></value></property>
</bean>
</beans>

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import java.util.Locale;
public class ACATester implements ApplicationContextAware {
private ApplicationContext ac;
public void setApplicationContext(ApplicationContext ctx) throws ApplicationContextException {
// check reinitialization
if (this.ac != null) {
throw new IllegalStateException("Already initialized");
}
// check message source availability
if (ctx != null) {
try {
ctx.getMessage("code1", null, Locale.getDefault());
}
catch (NoSuchMessageException ex) {
// expected
}
}
this.ac = ctx;
}
public ApplicationContext getApplicationContext() {
return ac;
}
}

View File

@@ -0,0 +1,157 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import java.util.Locale;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.AbstractListableBeanFactoryTests;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.LifecycleBean;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractApplicationContextTests extends AbstractListableBeanFactoryTests {
/** Must be supplied as XML */
public static final String TEST_NAMESPACE = "testNamespace";
protected ConfigurableApplicationContext applicationContext;
/** Subclass must register this */
protected TestListener listener = new TestListener();
protected TestListener parentListener = new TestListener();
protected void setUp() throws Exception {
this.applicationContext = createContext();
}
protected BeanFactory getBeanFactory() {
return applicationContext;
}
protected ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* Must register a TestListener.
* Must register standard beans.
* Parent must register rod with name Roderick
* and father with name Albert.
*/
protected abstract ConfigurableApplicationContext createContext() throws Exception;
public void testContextAwareSingletonWasCalledBack() throws Exception {
ACATester aca = (ACATester) applicationContext.getBean("aca");
assertTrue("has had context set", aca.getApplicationContext() == applicationContext);
Object aca2 = applicationContext.getBean("aca");
assertTrue("Same instance", aca == aca2);
assertTrue("Says is singleton", applicationContext.isSingleton("aca"));
}
public void testContextAwarePrototypeWasCalledBack() throws Exception {
ACATester aca = (ACATester) applicationContext.getBean("aca-prototype");
assertTrue("has had context set", aca.getApplicationContext() == applicationContext);
Object aca2 = applicationContext.getBean("aca-prototype");
assertTrue("NOT Same instance", aca != aca2);
assertTrue("Says is prototype", !applicationContext.isSingleton("aca-prototype"));
}
public void testParentNonNull() {
assertTrue("parent isn't null", applicationContext.getParent() != null);
}
public void testGrandparentNull() {
assertTrue("grandparent is null", applicationContext.getParent().getParent() == null);
}
public void testOverrideWorked() throws Exception {
TestBean rod = (TestBean) applicationContext.getParent().getBean("rod");
assertTrue("Parent's name differs", rod.getName().equals("Roderick"));
}
public void testGrandparentDefinitionFound() throws Exception {
TestBean dad = (TestBean) applicationContext.getBean("father");
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
}
public void testGrandparentTypedDefinitionFound() throws Exception {
TestBean dad = (TestBean) applicationContext.getBean("father", TestBean.class);
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
}
public void testCloseTriggersDestroy() {
LifecycleBean lb = (LifecycleBean) applicationContext.getBean("lifecycle");
assertTrue("Not destroyed", !lb.isDestroyed());
applicationContext.close();
if (applicationContext.getParent() != null) {
((ConfigurableApplicationContext) applicationContext.getParent()).close();
}
assertTrue("Destroyed", lb.isDestroyed());
applicationContext.close();
if (applicationContext.getParent() != null) {
((ConfigurableApplicationContext) applicationContext.getParent()).close();
}
assertTrue("Destroyed", lb.isDestroyed());
}
public void testMessageSource() throws NoSuchMessageException {
assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault()));
assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault()));
try {
applicationContext.getMessage("code0", null, Locale.getDefault());
fail("looking for code0 should throw a NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// that's how it should be
}
}
public void testEvents() throws Exception {
listener.zeroCounter();
parentListener.zeroCounter();
assertTrue("0 events before publication", listener.getEventCount() == 0);
assertTrue("0 parent events before publication", parentListener.getEventCount() == 0);
this.applicationContext.publishEvent(new MyEvent(this));
assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1);
assertTrue("1 parent events after publication", parentListener.getEventCount() == 1);
}
public void testBeanAutomaticallyHearsEvents() throws Exception {
//String[] listenerNames = ((ListableBeanFactory) applicationContext).getBeanDefinitionNames(ApplicationListener.class);
//assertTrue("listeners include beanThatListens", Arrays.asList(listenerNames).contains("beanThatListens"));
BeanThatListens b = (BeanThatListens) applicationContext.getBean("beanThatListens");
b.zero();
assertTrue("0 events before publication", b.getEventCount() == 0);
this.applicationContext.publishEvent(new MyEvent(this));
assertTrue("1 events after publication, not " + b.getEventCount(), b.getEventCount() == 1);
}
public static class MyEvent extends ApplicationEvent {
public MyEvent(Object source) {
super(source);
}
}
}

View File

@@ -33,4 +33,4 @@ public class BeanThatBroadcasts implements ApplicationContextAware {
}
}
}
}

View File

@@ -19,7 +19,7 @@ package org.springframework.context;
import java.util.Map;
/**
* A stub {@link org.springframework.context.ApplicationListener}.
* A stub {@link ApplicationListener}.
*
* @author Thomas Risberg
* @author Juergen Hoeller
@@ -58,4 +58,4 @@ public class BeanThatListens implements ApplicationListener {
eventCount = 0;
}
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.LifecycleBean;
/**
* Simple bean to test ApplicationContext lifecycle methods for beans
*
* @author Colin Sampaleanu
* @since 03.07.2004
*/
public class LifecycleContextBean extends LifecycleBean implements ApplicationContextAware {
protected ApplicationContext owningContext;
public void setBeanFactory(BeanFactory beanFactory) {
super.setBeanFactory(beanFactory);
if (this.owningContext != null)
throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
}
public void afterPropertiesSet() {
super.afterPropertiesSet();
if (this.owningContext == null)
throw new RuntimeException("Factory didn't call setAppliationContext before afterPropertiesSet on lifecycle bean");
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (this.owningFactory == null)
throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
this.owningContext = applicationContext;
}
}

View File

@@ -0,0 +1,104 @@
/*
* 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.context.support;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* @author Mark Fisher
* @author Chris Beams
*/
public class ApplicationContextLifecycleTests {
@Test
public void testBeansStart() {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("lifecycleTests.xml", getClass());
context.start();
LifecycleTestBean bean1 = (LifecycleTestBean) context.getBean("bean1");
LifecycleTestBean bean2 = (LifecycleTestBean) context.getBean("bean2");
LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3");
LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4");
String error = "bean was not started";
assertTrue(error, bean1.isRunning());
assertTrue(error, bean2.isRunning());
assertTrue(error, bean3.isRunning());
assertTrue(error, bean4.isRunning());
}
@Test
public void testBeansStop() {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("lifecycleTests.xml", getClass());
context.start();
LifecycleTestBean bean1 = (LifecycleTestBean) context.getBean("bean1");
LifecycleTestBean bean2 = (LifecycleTestBean) context.getBean("bean2");
LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3");
LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4");
String startError = "bean was not started";
assertTrue(startError, bean1.isRunning());
assertTrue(startError, bean2.isRunning());
assertTrue(startError, bean3.isRunning());
assertTrue(startError, bean4.isRunning());
context.stop();
String stopError = "bean was not stopped";
assertFalse(stopError, bean1.isRunning());
assertFalse(stopError, bean2.isRunning());
assertFalse(stopError, bean3.isRunning());
assertFalse(stopError, bean4.isRunning());
}
@Test
public void testStartOrder() {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("lifecycleTests.xml", getClass());
context.start();
LifecycleTestBean bean1 = (LifecycleTestBean) context.getBean("bean1");
LifecycleTestBean bean2 = (LifecycleTestBean) context.getBean("bean2");
LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3");
LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4");
String notStartedError = "bean was not started";
assertTrue(notStartedError, bean1.getStartOrder() > 0);
assertTrue(notStartedError, bean2.getStartOrder() > 0);
assertTrue(notStartedError, bean3.getStartOrder() > 0);
assertTrue(notStartedError, bean4.getStartOrder() > 0);
String orderError = "dependent bean must start after the bean it depends on";
assertTrue(orderError, bean2.getStartOrder() > bean1.getStartOrder());
assertTrue(orderError, bean3.getStartOrder() > bean2.getStartOrder());
assertTrue(orderError, bean4.getStartOrder() > bean2.getStartOrder());
}
@Test
public void testStopOrder() {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("lifecycleTests.xml", getClass());
context.start();
context.stop();
LifecycleTestBean bean1 = (LifecycleTestBean) context.getBean("bean1");
LifecycleTestBean bean2 = (LifecycleTestBean) context.getBean("bean2");
LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3");
LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4");
String notStoppedError = "bean was not stopped";
assertTrue(notStoppedError, bean1.getStopOrder() > 0);
assertTrue(notStoppedError, bean2.getStopOrder() > 0);
assertTrue(notStoppedError, bean3.getStopOrder() > 0);
assertTrue(notStoppedError, bean4.getStopOrder() > 0);
String orderError = "dependent bean must stop before the bean it depends on";
assertTrue(orderError, bean2.getStopOrder() < bean1.getStopOrder());
assertTrue(orderError, bean3.getStopOrder() < bean2.getStopOrder());
assertTrue(orderError, bean4.getStopOrder() < bean2.getStopOrder());
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
/**
* @author Alef Arendsen
*/
public class Assembler implements TestIF {
private Service service;
private Logic l;
private String name;
public void setService(Service service) {
this.service = service;
}
public void setLogic(Logic l) {
this.l = l;
}
public void setBeanName(String name) {
this.name = name;
}
public void test() {
}
public void output() {
System.out.println("Bean " + name);
l.output();
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import org.springframework.context.MessageSource;
/**
* @author Juergen Hoeller
*/
public class AutowiredService {
private MessageSource messageSource;
public void setMessageSource(MessageSource messageSource) {
if (this.messageSource != null) {
throw new IllegalArgumentException("MessageSource should not be set twice");
}
this.messageSource = messageSource;
}
public MessageSource getMessageSource() {
return messageSource;
}
}

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.context.support;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.ResourceTestBean;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.CannotLoadBeanClassException;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ObjectUtils;
/**
* @author Juergen Hoeller
*/
public class ClassPathXmlApplicationContextTests extends TestCase {
public void testSingleConfigLocation() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"/org/springframework/context/support/simpleContext.xml");
assertTrue(ctx.containsBean("someMessageSource"));
ctx.close();
}
public void testMultipleConfigLocations() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] {
"/org/springframework/context/support/test/contextB.xml",
"/org/springframework/context/support/test/contextC.xml",
"/org/springframework/context/support/test/contextA.xml"});
assertTrue(ctx.containsBean("service"));
assertTrue(ctx.containsBean("logicOne"));
assertTrue(ctx.containsBean("logicTwo"));
Service service = (Service) ctx.getBean("service");
ctx.refresh();
assertTrue(service.isProperlyDestroyed());
service = (Service) ctx.getBean("service");
ctx.close();
assertTrue(service.isProperlyDestroyed());
}
public void testConfigLocationPattern() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"/org/springframework/context/support/test/context*.xml");
assertTrue(ctx.containsBean("service"));
assertTrue(ctx.containsBean("logicOne"));
assertTrue(ctx.containsBean("logicTwo"));
Service service = (Service) ctx.getBean("service");
ctx.close();
assertTrue(service.isProperlyDestroyed());
}
public void testSingleConfigLocationWithClass() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"simpleContext.xml", getClass());
assertTrue(ctx.containsBean("someMessageSource"));
ctx.close();
}
public void testAliasWithPlaceholder() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] {
"/org/springframework/context/support/test/contextB.xml",
"/org/springframework/context/support/test/aliased-contextC.xml",
"/org/springframework/context/support/test/contextA.xml"});
assertTrue(ctx.containsBean("service"));
assertTrue(ctx.containsBean("logicOne"));
assertTrue(ctx.containsBean("logicTwo"));
ctx.refresh();
}
public void testContextWithInvalidValueType() throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"/org/springframework/context/support/invalidValueType.xml"}, false);
try {
context.refresh();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.contains(TypeMismatchException.class));
assertTrue(ex.toString().indexOf("someMessageSource") != -1);
assertTrue(ex.toString().indexOf("useCodeAsDefaultMessage") != -1);
checkExceptionFromInvalidValueType(ex);
checkExceptionFromInvalidValueType(new ExceptionInInitializerError(ex));
assertFalse(context.isActive());
}
}
private void checkExceptionFromInvalidValueType(Throwable ex) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ex.printStackTrace(new PrintStream(baos));
String dump = FileCopyUtils.copyToString(
new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));
assertTrue(dump.indexOf("someMessageSource") != -1);
assertTrue(dump.indexOf("useCodeAsDefaultMessage") != -1);
}
public void testContextWithInvalidLazyClass() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"invalidClass.xml", getClass());
assertTrue(ctx.containsBean("someMessageSource"));
try {
ctx.getBean("someMessageSource");
fail("Should have thrown CannotLoadBeanClassException");
}
catch (CannotLoadBeanClassException ex) {
assertTrue(ex.contains(ClassNotFoundException.class));
}
ctx.close();
}
public void testContextWithClassNameThatContainsPlaceholder() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"classWithPlaceholder.xml", getClass());
assertTrue(ctx.containsBean("someMessageSource"));
assertTrue(ctx.getBean("someMessageSource") instanceof StaticMessageSource);
ctx.close();
}
public void testMultipleConfigLocationsWithClass() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] {"test/contextB.xml", "test/contextC.xml", "test/contextA.xml"}, getClass());
assertTrue(ctx.containsBean("service"));
assertTrue(ctx.containsBean("logicOne"));
assertTrue(ctx.containsBean("logicTwo"));
ctx.close();
}
public void testFactoryBeanAndApplicationListener() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"/org/springframework/context/support/test/context*.xml");
ctx.getBeanFactory().registerSingleton("manualFBAAL", new FactoryBeanAndApplicationListener());
assertEquals(2, ctx.getBeansOfType(ApplicationListener.class).size());
ctx.close();
}
public void testMessageSourceAware() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"/org/springframework/context/support/test/context*.xml");
MessageSource messageSource = (MessageSource) ctx.getBean("messageSource");
Service service1 = (Service) ctx.getBean("service");
assertEquals(ctx, service1.getMessageSource());
Service service2 = (Service) ctx.getBean("service2");
assertEquals(ctx, service2.getMessageSource());
AutowiredService autowiredService1 = (AutowiredService) ctx.getBean("autowiredService");
assertEquals(messageSource, autowiredService1.getMessageSource());
AutowiredService autowiredService2 = (AutowiredService) ctx.getBean("autowiredService2");
assertEquals(messageSource, autowiredService2.getMessageSource());
ctx.close();
}
public void testResourceArrayPropertyEditor() throws IOException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"/org/springframework/context/support/test/context*.xml");
Service service = (Service) ctx.getBean("service");
assertEquals(3, service.getResources().length);
List resources = Arrays.asList(service.getResources());
assertTrue(resources.contains(
new FileSystemResource(new ClassPathResource("/org/springframework/context/support/test/contextA.xml").getFile())));
assertTrue(resources.contains(
new FileSystemResource(new ClassPathResource("/org/springframework/context/support/test/contextB.xml").getFile())));
assertTrue(resources.contains(
new FileSystemResource(new ClassPathResource("/org/springframework/context/support/test/contextC.xml").getFile())));
ctx.close();
}
public void testChildWithProxy() throws Exception {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"/org/springframework/context/support/test/context*.xml");
ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext(
new String[] {"/org/springframework/context/support/childWithProxy.xml"}, ctx);
assertTrue(AopUtils.isAopProxy(child.getBean("assemblerOne")));
assertTrue(AopUtils.isAopProxy(child.getBean("assemblerTwo")));
ctx.close();
}
public void testAliasForParentContext() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"/org/springframework/context/support/simpleContext.xml");
assertTrue(ctx.containsBean("someMessageSource"));
ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext(
new String[] {"/org/springframework/context/support/aliasForParent.xml"}, ctx);
assertTrue(child.containsBean("someMessageSource"));
assertTrue(child.containsBean("yourMessageSource"));
assertTrue(child.containsBean("myMessageSource"));
assertTrue(child.isSingleton("someMessageSource"));
assertTrue(child.isSingleton("yourMessageSource"));
assertTrue(child.isSingleton("myMessageSource"));
assertEquals(StaticMessageSource.class, child.getType("someMessageSource"));
assertEquals(StaticMessageSource.class, child.getType("yourMessageSource"));
assertEquals(StaticMessageSource.class, child.getType("myMessageSource"));
Object someMs = child.getBean("someMessageSource");
Object yourMs = child.getBean("yourMessageSource");
Object myMs = child.getBean("myMessageSource");
assertSame(someMs, yourMs);
assertSame(someMs, myMs);
String[] aliases = child.getAliases("someMessageSource");
assertEquals(2, aliases.length);
assertEquals("myMessageSource", aliases[0]);
assertEquals("yourMessageSource", aliases[1]);
aliases = child.getAliases("myMessageSource");
assertEquals(2, aliases.length);
assertEquals("someMessageSource", aliases[0]);
assertEquals("yourMessageSource", aliases[1]);
child.close();
ctx.close();
}
public void testAliasThatOverridesParent() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"/org/springframework/context/support/simpleContext.xml");
Object someMs = ctx.getBean("someMessageSource");
ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext(
new String[] {"/org/springframework/context/support/aliasThatOverridesParent.xml"}, ctx);
Object myMs = child.getBean("myMessageSource");
Object someMs2 = child.getBean("someMessageSource");
assertSame(myMs, someMs2);
assertNotSame(someMs, someMs2);
assertOneMessageSourceOnly(child, myMs);
}
public void testAliasThatOverridesEarlierBean() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] {"/org/springframework/context/support/simpleContext.xml",
"/org/springframework/context/support/aliasThatOverridesParent.xml"});
Object myMs = ctx.getBean("myMessageSource");
Object someMs2 = ctx.getBean("someMessageSource");
assertSame(myMs, someMs2);
assertOneMessageSourceOnly(ctx, myMs);
}
private void assertOneMessageSourceOnly(ClassPathXmlApplicationContext ctx, Object myMessageSource) {
String[] beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class);
assertEquals(1, beanNamesForType.length);
assertEquals("myMessageSource", beanNamesForType[0]);
beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class, true, true);
assertEquals(1, beanNamesForType.length);
assertEquals("myMessageSource", beanNamesForType[0]);
beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class);
assertEquals(1, beanNamesForType.length);
assertEquals("myMessageSource", beanNamesForType[0]);
beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true);
assertEquals(1, beanNamesForType.length);
assertEquals("myMessageSource", beanNamesForType[0]);
Map beansOfType = ctx.getBeansOfType(StaticMessageSource.class);
assertEquals(1, beansOfType.size());
assertSame(myMessageSource, beansOfType.values().iterator().next());
beansOfType = ctx.getBeansOfType(StaticMessageSource.class, true, true);
assertEquals(1, beansOfType.size());
assertSame(myMessageSource, beansOfType.values().iterator().next());
beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class);
assertEquals(1, beansOfType.size());
assertSame(myMessageSource, beansOfType.values().iterator().next());
beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true);
assertEquals(1, beansOfType.size());
assertSame(myMessageSource, beansOfType.values().iterator().next());
}
public void testResourceAndInputStream() throws IOException {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("/org/springframework/beans/factory/xml/resource.xml") {
public Resource getResource(String location) {
if ("classpath:org/springframework/beans/factory/xml/test.properties".equals(location)) {
return new ClassPathResource("test.properties", ClassPathXmlApplicationContextTests.class);
}
return super.getResource(location);
}
};
ResourceTestBean resource1 = (ResourceTestBean) ctx.getBean("resource1");
ResourceTestBean resource2 = (ResourceTestBean) ctx.getBean("resource2");
assertTrue(resource1.getResource() instanceof ClassPathResource);
StringWriter writer = new StringWriter();
FileCopyUtils.copy(new InputStreamReader(resource1.getResource().getInputStream()), writer);
assertEquals("contexttest", writer.toString());
writer = new StringWriter();
FileCopyUtils.copy(new InputStreamReader(resource1.getInputStream()), writer);
assertEquals("contexttest", writer.toString());
writer = new StringWriter();
FileCopyUtils.copy(new InputStreamReader(resource2.getResource().getInputStream()), writer);
assertEquals("contexttest", writer.toString());
writer = new StringWriter();
FileCopyUtils.copy(new InputStreamReader(resource2.getInputStream()), writer);
assertEquals("contexttest", writer.toString());
ctx.close();
}
public void testGenericApplicationContextWithXmlBeanDefinitions() {
GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);
reader.loadBeanDefinitions(new ClassPathResource("test/contextB.xml", getClass()));
reader.loadBeanDefinitions(new ClassPathResource("test/contextC.xml", getClass()));
reader.loadBeanDefinitions(new ClassPathResource("test/contextA.xml", getClass()));
ctx.refresh();
assertTrue(ctx.containsBean("service"));
assertTrue(ctx.containsBean("logicOne"));
assertTrue(ctx.containsBean("logicTwo"));
ctx.close();
}
public void testGenericApplicationContextWithXmlBeanDefinitionsAndClassLoaderNull() {
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.setClassLoader(null);
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);
reader.loadBeanDefinitions(new ClassPathResource("test/contextB.xml", getClass()));
reader.loadBeanDefinitions(new ClassPathResource("test/contextC.xml", getClass()));
reader.loadBeanDefinitions(new ClassPathResource("test/contextA.xml", getClass()));
ctx.refresh();
assertEquals(ObjectUtils.identityToString(ctx), ctx.getId());
assertEquals(ObjectUtils.identityToString(ctx), ctx.getDisplayName());
assertTrue(ctx.containsBean("service"));
assertTrue(ctx.containsBean("logicOne"));
assertTrue(ctx.containsBean("logicTwo"));
ctx.close();
}
public void testGenericApplicationContextWithXmlBeanDefinitionsAndSpecifiedId() {
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.setId("testContext");
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);
reader.loadBeanDefinitions(new ClassPathResource("test/contextB.xml", getClass()));
reader.loadBeanDefinitions(new ClassPathResource("test/contextC.xml", getClass()));
reader.loadBeanDefinitions(new ClassPathResource("test/contextA.xml", getClass()));
ctx.refresh();
assertEquals("testContext", ctx.getId());
assertEquals("testContext", ctx.getDisplayName());
assertTrue(ctx.containsBean("service"));
assertTrue(ctx.containsBean("logicOne"));
assertTrue(ctx.containsBean("logicTwo"));
ctx.close();
}
}

View File

@@ -0,0 +1,28 @@
package org.springframework.context.support;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
/**
* @author Juergen Hoeller
* @since 06.10.2004
*/
public class FactoryBeanAndApplicationListener implements FactoryBean, ApplicationListener {
public Object getObject() throws Exception {
return "";
}
public Class getObjectType() {
return String.class;
}
public boolean isSingleton() {
return true;
}
public void onApplicationEvent(ApplicationEvent event) {
}
}

View File

@@ -0,0 +1,60 @@
/*
* 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.context.support;
import org.springframework.context.Lifecycle;
/**
* @author Mark Fisher
*/
public class LifecycleTestBean implements Lifecycle {
private static int startCounter;
private static int stopCounter;
private int startOrder;
private int stopOrder;
private boolean running;
public int getStartOrder() {
return startOrder;
}
public int getStopOrder() {
return stopOrder;
}
public boolean isRunning() {
return this.running;
}
public void start() {
this.startOrder = ++startCounter;
this.running = true;
}
public void stop() {
this.stopOrder = ++stopCounter;
this.running = false;
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanNameAware;
public class Logic implements BeanNameAware {
private Log log = LogFactory.getLog(Logic.class);
private String name;
private Assembler a;
public void setAssembler(Assembler a) {
this.a = a;
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String)
*/
public void setBeanName(String name) {
this.name = name;
}
public void output() {
System.out.println("Bean " + name);
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import org.springframework.aop.ThrowsAdvice;
/**
* Advice object that implements <i>multiple</i> Advice interfaces.
*
* @author Chris Beams
*/
public class NoOpAdvice implements ThrowsAdvice {
public void afterThrowing(Exception ex) throws Throwable {
// no-op
}
}

View File

@@ -0,0 +1,270 @@
/*
* 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.context.support;
import java.util.Locale;
import java.util.Properties;
import junit.framework.TestCase;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.JdkVersion;
/**
* @author Juergen Hoeller
* @since 03.02.2004
*/
public class ResourceBundleMessageSourceTests extends TestCase {
public void testMessageAccessWithDefaultMessageSource() {
doTestMessageAccess(false, true, false, false, false);
}
public void testMessageAccessWithDefaultMessageSourceAndMessageFormat() {
doTestMessageAccess(false, true, false, false, true);
}
public void testMessageAccessWithDefaultMessageSourceAndFallbackToGerman() {
doTestMessageAccess(false, true, true, true, false);
}
public void testMessageAccessWithReloadableMessageSource() {
doTestMessageAccess(true, true, false, false, false);
}
public void testMessageAccessWithReloadableMessageSourceAndMessageFormat() {
doTestMessageAccess(true, true, false, false, true);
}
public void testMessageAccessWithReloadableMessageSourceAndFallbackToGerman() {
doTestMessageAccess(true, true, true, true, false);
}
public void testMessageAccessWithReloadableMessageSourceAndFallbackTurnedOff() {
doTestMessageAccess(true, false, false, false, false);
}
public void testMessageAccessWithReloadableMessageSourceAndFallbackTurnedOffAndFallbackToGerman() {
doTestMessageAccess(true, false, true, true, false);
}
protected void doTestMessageAccess(
boolean reloadable, boolean fallbackToSystemLocale,
boolean expectGermanFallback, boolean useCodeAsDefaultMessage, boolean alwaysUseMessageFormat) {
StaticApplicationContext ac = new StaticApplicationContext();
if (reloadable) {
StaticApplicationContext parent = new StaticApplicationContext();
parent.refresh();
ac.setParent(parent);
}
MutablePropertyValues pvs = new MutablePropertyValues();
String basepath = "org/springframework/context/support/";
String[] basenames = null;
if (reloadable) {
basenames = new String[] {
"classpath:" + basepath + "messages",
"classpath:" + basepath + "more-messages"};
}
else {
basenames = new String[] {
basepath + "messages",
basepath + "more-messages"};
}
pvs.addPropertyValue("basenames", basenames);
if (!fallbackToSystemLocale) {
pvs.addPropertyValue("fallbackToSystemLocale", Boolean.FALSE);
}
if (useCodeAsDefaultMessage) {
pvs.addPropertyValue("useCodeAsDefaultMessage", Boolean.TRUE);
}
if (alwaysUseMessageFormat) {
pvs.addPropertyValue("alwaysUseMessageFormat", Boolean.TRUE);
}
Class clazz = reloadable ?
(Class) ReloadableResourceBundleMessageSource.class : ResourceBundleMessageSource.class;
ac.registerSingleton("messageSource", clazz, pvs);
ac.refresh();
Locale.setDefault(expectGermanFallback ? Locale.GERMAN : Locale.CANADA);
assertEquals("message1", ac.getMessage("code1", null, Locale.ENGLISH));
assertEquals(fallbackToSystemLocale && expectGermanFallback ? "nachricht2" : "message2",
ac.getMessage("code2", null, Locale.ENGLISH));
assertEquals("nachricht2", ac.getMessage("code2", null, Locale.GERMAN));
assertEquals("nochricht2", ac.getMessage("code2", null, new Locale("DE", "at")));
assertEquals("noochricht2", ac.getMessage("code2", null, new Locale("DE", "at", "oo")));
if (reloadable && JdkVersion.getMajorJavaVersion() >= JdkVersion.JAVA_15) {
assertEquals("nachricht2xml", ac.getMessage("code2", null, Locale.GERMANY));
}
MessageSourceAccessor accessor = new MessageSourceAccessor(ac);
LocaleContextHolder.setLocale(new Locale("DE", "at"));
try {
assertEquals("nochricht2", accessor.getMessage("code2"));
}
finally {
LocaleContextHolder.setLocale(null);
}
assertEquals("message3", ac.getMessage("code3", null, Locale.ENGLISH));
MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable("code3");
assertEquals("message3", ac.getMessage(resolvable, Locale.ENGLISH));
resolvable = new DefaultMessageSourceResolvable(new String[] {"code4", "code3"});
assertEquals("message3", ac.getMessage(resolvable, Locale.ENGLISH));
assertEquals("message3", ac.getMessage("code3", null, Locale.ENGLISH));
resolvable = new DefaultMessageSourceResolvable(new String[] {"code4", "code3"});
assertEquals("message3", ac.getMessage(resolvable, Locale.ENGLISH));
Object[] args = new Object[] {"Hello", new DefaultMessageSourceResolvable(new String[] {"code1"})};
assertEquals("Hello, message1", ac.getMessage("hello", args, Locale.ENGLISH));
// test default message without and with args
assertEquals("default", ac.getMessage(null, null, "default", Locale.ENGLISH));
assertEquals("default", ac.getMessage(null, args, "default", Locale.ENGLISH));
assertEquals("{0}, default", ac.getMessage(null, null, "{0}, default", Locale.ENGLISH));
assertEquals("Hello, default", ac.getMessage(null, args, "{0}, default", Locale.ENGLISH));
// test resolvable with default message, without and with args
resolvable = new DefaultMessageSourceResolvable(null, null, "default");
assertEquals("default", ac.getMessage(resolvable, Locale.ENGLISH));
resolvable = new DefaultMessageSourceResolvable(null, args, "default");
assertEquals("default", ac.getMessage(resolvable, Locale.ENGLISH));
resolvable = new DefaultMessageSourceResolvable(null, null, "{0}, default");
assertEquals("{0}, default", ac.getMessage(resolvable, Locale.ENGLISH));
resolvable = new DefaultMessageSourceResolvable(null, args, "{0}, default");
assertEquals("Hello, default", ac.getMessage(resolvable, Locale.ENGLISH));
// test message args
assertEquals("Arg1, Arg2", ac.getMessage("hello", new Object[] {"Arg1", "Arg2"}, Locale.ENGLISH));
assertEquals("{0}, {1}", ac.getMessage("hello", null, Locale.ENGLISH));
if (alwaysUseMessageFormat) {
assertEquals("I'm", ac.getMessage("escaped", null, Locale.ENGLISH));
}
else {
assertEquals("I''m", ac.getMessage("escaped", null, Locale.ENGLISH));
}
assertEquals("I'm", ac.getMessage("escaped", new Object[] {"some arg"}, Locale.ENGLISH));
try {
assertEquals("code4", ac.getMessage("code4", null, Locale.GERMAN));
if (!useCodeAsDefaultMessage) {
fail("Should have thrown NoSuchMessageException");
}
}
catch (NoSuchMessageException ex) {
if (useCodeAsDefaultMessage) {
fail("Should have returned code as default message");
}
}
}
public void testDefaultApplicationContextMessageSource() {
GenericApplicationContext ac = new GenericApplicationContext();
ac.refresh();
assertEquals("default", ac.getMessage("code1", null, "default", Locale.ENGLISH));
assertEquals("default value", ac.getMessage("code1", new Object[] {"value"}, "default {0}", Locale.ENGLISH));
}
public void testResourceBundleMessageSourceStandalone() {
ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
ms.setBasename("org/springframework/context/support/messages");
assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH));
assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN));
}
public void testResourceBundleMessageSourceWithWhitespaceInBasename() {
ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
ms.setBasename(" org/springframework/context/support/messages ");
assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH));
assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN));
}
public void testReloadableResourceBundleMessageSourceStandalone() {
ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
ms.setBasename("org/springframework/context/support/messages");
assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH));
assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN));
}
public void testReloadableResourceBundleMessageSourceWithWhitespaceInBasename() {
ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
ms.setBasename(" org/springframework/context/support/messages ");
assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH));
assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN));
}
public void testReloadableResourceBundleMessageSourceWithDefaultCharset() {
ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
ms.setBasename("org/springframework/context/support/messages");
ms.setDefaultEncoding("ISO-8859-1");
assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH));
assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN));
}
public void testReloadableResourceBundleMessageSourceWithInappropriateDefaultCharset() {
ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
ms.setBasename("org/springframework/context/support/messages");
ms.setDefaultEncoding("unicode");
Properties fileCharsets = new Properties();
fileCharsets.setProperty("org/springframework/context/support/messages_de", "unicode");
ms.setFileEncodings(fileCharsets);
ms.setFallbackToSystemLocale(false);
try {
ms.getMessage("code1", null, Locale.ENGLISH);
fail("Should have thrown NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// expected
}
}
public void testReloadableResourceBundleMessageSourceWithInappropriateEnglishCharset() {
ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
ms.setBasename("org/springframework/context/support/messages");
ms.setFallbackToSystemLocale(false);
Properties fileCharsets = new Properties();
fileCharsets.setProperty("org/springframework/context/support/messages", "unicode");
ms.setFileEncodings(fileCharsets);
try {
ms.getMessage("code1", null, Locale.ENGLISH);
fail("Should have thrown NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// expected
}
}
public void testReloadableResourceBundleMessageSourceWithInappropriateGermanCharset() {
ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource();
ms.setBasename("org/springframework/context/support/messages");
ms.setFallbackToSystemLocale(false);
Properties fileCharsets = new Properties();
fileCharsets.setProperty("org/springframework/context/support/messages_de", "unicode");
ms.setFileEncodings(fileCharsets);
assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH));
assertEquals("message2", ms.getMessage("code2", null, Locale.GERMAN));
}
}

View File

@@ -0,0 +1,95 @@
/*
* 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.context.support;
import org.springframework.beans.factory.BeanCreationNotAllowedException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
/**
* @author Alef Arendsen
* @author Juergen Hoeller
*/
public class Service implements ApplicationContextAware, MessageSourceAware, DisposableBean {
private ApplicationContext applicationContext;
private MessageSource messageSource;
private Resource[] resources;
private boolean properlyDestroyed = false;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public void setMessageSource(MessageSource messageSource) {
if (this.messageSource != null) {
throw new IllegalArgumentException("MessageSource should not be set twice");
}
this.messageSource = messageSource;
}
public MessageSource getMessageSource() {
return messageSource;
}
public void setResources(Resource[] resources) {
this.resources = resources;
}
public Resource[] getResources() {
return resources;
}
public void destroy() {
this.properlyDestroyed = true;
Thread thread = new Thread() {
public void run() {
Assert.isTrue(applicationContext.getBean("messageSource") instanceof StaticMessageSource);
try {
applicationContext.getBean("service2");
// Should have thrown BeanCreationNotAllowedException
properlyDestroyed = false;
}
catch (BeanCreationNotAllowedException ex) {
// expected
}
}
};
thread.start();
try {
thread.join();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public boolean isProperlyDestroyed() {
return properlyDestroyed;
}
}

View File

@@ -0,0 +1,97 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.context.ACATester;
import org.springframework.context.AbstractApplicationContextTests;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.BeanThatListens;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
/**
* Tests for static application context with custom application event multicaster.
*
* @author Juergen Hoeller
*/
public class StaticApplicationContextMulticasterTests extends AbstractApplicationContextTests {
protected StaticApplicationContext sac;
/** Run for each test */
protected ConfigurableApplicationContext createContext() throws Exception {
StaticApplicationContext parent = new StaticApplicationContext();
Map m = new HashMap();
m.put("name", "Roderick");
parent.registerPrototype("rod", TestBean.class, new MutablePropertyValues(m));
m.put("name", "Albert");
parent.registerPrototype("father", TestBean.class, new MutablePropertyValues(m));
parent.registerSingleton(StaticApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
TestApplicationEventMulticaster.class, null);
parent.refresh();
parent.addListener(parentListener) ;
parent.getStaticMessageSource().addMessage("code1", Locale.getDefault(), "message1");
this.sac = new StaticApplicationContext(parent);
sac.registerSingleton("beanThatListens", BeanThatListens.class, new MutablePropertyValues());
sac.registerSingleton("aca", ACATester.class, new MutablePropertyValues());
sac.registerPrototype("aca-prototype", ACATester.class, new MutablePropertyValues());
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(sac.getDefaultListableBeanFactory());
Resource resource = new ClassPathResource("testBeans.properties", getClass());
reader.loadBeanDefinitions(new EncodedResource(resource, "ISO-8859-1"));
sac.refresh();
sac.addListener(listener);
sac.getStaticMessageSource().addMessage("code2", Locale.getDefault(), "message2");
return sac;
}
/** Overridden */
public void testCount() {
assertCount(15);
}
public void testEvents() throws Exception {
TestApplicationEventMulticaster.counter = 0;
super.testEvents();
assertEquals(1, TestApplicationEventMulticaster.counter);
}
public static class TestApplicationEventMulticaster extends SimpleApplicationEventMulticaster {
private static int counter = 0;
public void multicastEvent(ApplicationEvent event) {
super.multicastEvent(event);
counter++;
}
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.context.ACATester;
import org.springframework.context.AbstractApplicationContextTests;
import org.springframework.context.BeanThatListens;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.ClassPathResource;
/**
* Tests for static application context.
*
* @author Rod Johnson
*/
public class StaticApplicationContextTests extends AbstractApplicationContextTests {
protected StaticApplicationContext sac;
/** Run for each test */
protected ConfigurableApplicationContext createContext() throws Exception {
StaticApplicationContext parent = new StaticApplicationContext();
Map m = new HashMap();
m.put("name", "Roderick");
parent.registerPrototype("rod", TestBean.class, new MutablePropertyValues(m));
m.put("name", "Albert");
parent.registerPrototype("father", TestBean.class, new MutablePropertyValues(m));
parent.refresh();
parent.addListener(parentListener) ;
parent.getStaticMessageSource().addMessage("code1", Locale.getDefault(), "message1");
this.sac = new StaticApplicationContext(parent);
sac.registerSingleton("beanThatListens", BeanThatListens.class, new MutablePropertyValues());
sac.registerSingleton("aca", ACATester.class, new MutablePropertyValues());
sac.registerPrototype("aca-prototype", ACATester.class, new MutablePropertyValues());
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(sac.getDefaultListableBeanFactory());
reader.loadBeanDefinitions(new ClassPathResource("testBeans.properties", getClass()));
sac.refresh();
sac.addListener(listener);
sac.getStaticMessageSource().addMessage("code2", Locale.getDefault(), "message2");
return sac;
}
/** Overridden */
public void testCount() {
assertCount(15);
}
}

View File

@@ -0,0 +1,262 @@
/*
* 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.context.support;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.context.ACATester;
import org.springframework.context.AbstractApplicationContextTests;
import org.springframework.context.BeanThatListens;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.core.io.ClassPathResource;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class StaticMessageSourceTests extends AbstractApplicationContextTests {
protected static final String MSG_TXT1_US =
"At '{1,time}' on \"{1,date}\", there was \"{2}\" on planet {0,number,integer}.";
protected static final String MSG_TXT1_UK =
"At '{1,time}' on \"{1,date}\", there was \"{2}\" on station number {0,number,integer}.";
protected static final String MSG_TXT2_US =
"This is a test message in the message catalog with no args.";
protected static final String MSG_TXT3_US =
"This is another test message in the message catalog with no args.";
protected StaticApplicationContext sac;
/** Overridden */
public void testCount() {
// These are only checked for current Ctx (not parent ctx)
assertCount(15);
}
public void testMessageSource() throws NoSuchMessageException {
// Do nothing here since super is looking for errorCodes we
// do NOT have in the Context
}
public void testGetMessageWithDefaultPassedInAndFoundInMsgCatalog() {
// Try with Locale.US
assertTrue("valid msg from staticMsgSource with default msg passed in returned msg from msg catalog for Locale.US",
sac.getMessage("message.format.example2", null, "This is a default msg if not found in MessageSource.", Locale.US)
.equals("This is a test message in the message catalog with no args."));
}
public void testGetMessageWithDefaultPassedInAndNotFoundInMsgCatalog() {
// Try with Locale.US
assertTrue("bogus msg from staticMsgSource with default msg passed in returned default msg for Locale.US",
sac.getMessage("bogus.message", null, "This is a default msg if not found in MessageSource.", Locale.US)
.equals("This is a default msg if not found in MessageSource."));
}
/**
* We really are testing the AbstractMessageSource class here.
* The underlying implementation uses a hashMap to cache messageFormats
* once a message has been asked for. This test is an attempt to
* make sure the cache is being used properly.
* @see org.springframework.context.support.AbstractMessageSource for more details.
*/
public void testGetMessageWithMessageAlreadyLookedFor() {
Object[] arguments = {
new Integer(7), new Date(System.currentTimeMillis()),
"a disturbance in the Force"
};
// The first time searching, we don't care about for this test
// Try with Locale.US
sac.getMessage("message.format.example1", arguments, Locale.US);
// Now msg better be as expected
assertTrue("2nd search within MsgFormat cache returned expected message for Locale.US",
sac.getMessage("message.format.example1", arguments, Locale.US).indexOf(
"there was \"a disturbance in the Force\" on planet 7.") != -1);
Object[] newArguments = {
new Integer(8), new Date(System.currentTimeMillis()),
"a disturbance in the Force"
};
// Now msg better be as expected even with different args
assertTrue("2nd search within MsgFormat cache with different args returned expected message for Locale.US",
sac.getMessage("message.format.example1", newArguments, Locale.US)
.indexOf("there was \"a disturbance in the Force\" on planet 8.") != -1);
}
/**
* Example taken from the javadocs for the java.text.MessageFormat class
*/
public void testGetMessageWithNoDefaultPassedInAndFoundInMsgCatalog() {
Object[] arguments = {
new Integer(7), new Date(System.currentTimeMillis()),
"a disturbance in the Force"
};
/*
Try with Locale.US
Since the msg has a time value in it, we will use String.indexOf(...)
to just look for a substring without the time. This is because it is
possible that by the time we store a time variable in this method
and the time the ResourceBundleMessageSource resolves the msg the
minutes of the time might not be the same.
*/
assertTrue("msg from staticMsgSource for Locale.US substituting args for placeholders is as expected",
sac.getMessage("message.format.example1", arguments, Locale.US)
.indexOf("there was \"a disturbance in the Force\" on planet 7.") != -1);
// Try with Locale.UK
assertTrue("msg from staticMsgSource for Locale.UK substituting args for placeholders is as expected",
sac.getMessage("message.format.example1", arguments, Locale.UK)
.indexOf("there was \"a disturbance in the Force\" on station number 7.") != -1);
// Try with Locale.US - Use a different test msg that requires no args
assertTrue("msg from staticMsgSource for Locale.US that requires no args is as expected",
sac.getMessage("message.format.example2", null, Locale.US)
.equals("This is a test message in the message catalog with no args."));
}
public void testGetMessageWithNoDefaultPassedInAndNotFoundInMsgCatalog() {
// Expecting an exception
try {
// Try with Locale.US
sac.getMessage("bogus.message", null, Locale.US);
fail("bogus msg from staticMsgSource for Locale.US without default msg should have thrown exception");
}
catch (NoSuchMessageException tExcept) {
assertTrue("bogus msg from staticMsgSource for Locale.US without default msg threw expected exception", true);
}
}
public void testMessageSourceResolvable() {
// first code valid
String[] codes1 = new String[] {"message.format.example3", "message.format.example2"};
MessageSourceResolvable resolvable1 = new DefaultMessageSourceResolvable(codes1, null, "default");
try {
assertTrue("correct message retrieved", MSG_TXT3_US.equals(sac.getMessage(resolvable1, Locale.US)));
}
catch (NoSuchMessageException ex) {
fail("Should not throw NoSuchMessageException");
}
// only second code valid
String[] codes2 = new String[] {"message.format.example99", "message.format.example2"};
MessageSourceResolvable resolvable2 = new DefaultMessageSourceResolvable(codes2, null, "default");
try {
assertTrue("correct message retrieved", MSG_TXT2_US.equals(sac.getMessage(resolvable2, Locale.US)));
}
catch (NoSuchMessageException ex) {
fail("Should not throw NoSuchMessageException");
}
// no code valid, but default given
String[] codes3 = new String[] {"message.format.example99", "message.format.example98"};
MessageSourceResolvable resolvable3 = new DefaultMessageSourceResolvable(codes3, null, "default");
try {
assertTrue("correct message retrieved", "default".equals(sac.getMessage(resolvable3, Locale.US)));
}
catch (NoSuchMessageException ex) {
fail("Should not throw NoSuchMessageException");
}
// no code valid, no default
String[] codes4 = new String[] {"message.format.example99", "message.format.example98"};
MessageSourceResolvable resolvable4 = new DefaultMessageSourceResolvable(codes4);
try {
sac.getMessage(resolvable4, Locale.US);
fail("Should have thrown NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// expected
}
}
/** Run for each test */
protected ConfigurableApplicationContext createContext() throws Exception {
StaticApplicationContext parent = new StaticApplicationContext();
Map m = new HashMap();
m.put("name", "Roderick");
parent.registerPrototype("rod", org.springframework.beans.TestBean.class, new MutablePropertyValues(m));
m.put("name", "Albert");
parent.registerPrototype("father", org.springframework.beans.TestBean.class, new MutablePropertyValues(m));
parent.refresh();
parent.addListener(parentListener);
this.sac = new StaticApplicationContext(parent);
sac.registerSingleton("beanThatListens", BeanThatListens.class, new MutablePropertyValues());
sac.registerSingleton("aca", ACATester.class, new MutablePropertyValues());
sac.registerPrototype("aca-prototype", ACATester.class, new MutablePropertyValues());
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(sac.getDefaultListableBeanFactory());
reader.loadBeanDefinitions(new ClassPathResource("testBeans.properties", getClass()));
sac.refresh();
sac.addListener(listener);
StaticMessageSource messageSource = sac.getStaticMessageSource();
Map usMessages = new HashMap(3);
usMessages.put("message.format.example1", MSG_TXT1_US);
usMessages.put("message.format.example2", MSG_TXT2_US);
usMessages.put("message.format.example3", MSG_TXT3_US);
messageSource.addMessages(usMessages, Locale.US);
messageSource.addMessage("message.format.example1", Locale.UK, MSG_TXT1_UK);
return sac;
}
public void testNestedMessageSourceWithParamInChild() {
StaticMessageSource source = new StaticMessageSource();
StaticMessageSource parent = new StaticMessageSource();
source.setParentMessageSource(parent);
source.addMessage("param", Locale.ENGLISH, "value");
parent.addMessage("with.param", Locale.ENGLISH, "put {0} here");
MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(
new String[] {"with.param"}, new Object[] {new DefaultMessageSourceResolvable("param")});
assertEquals("put value here", source.getMessage(resolvable, Locale.ENGLISH));
}
public void testNestedMessageSourceWithParamInParent() {
StaticMessageSource source = new StaticMessageSource();
StaticMessageSource parent = new StaticMessageSource();
source.setParentMessageSource(parent);
parent.addMessage("param", Locale.ENGLISH, "value");
source.addMessage("with.param", Locale.ENGLISH, "put {0} here");
MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(
new String[] {"with.param"}, new Object[] {new DefaultMessageSourceResolvable("param")});
assertEquals("put value here", source.getMessage(resolvable, Locale.ENGLISH));
}
}

View File

@@ -0,0 +1,21 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
public interface TestIF {
}

View File

@@ -0,0 +1,37 @@
/*
* 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.context.support;
import org.springframework.aop.framework.AbstractSingletonProxyFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean;
@SuppressWarnings("serial")
public class TestProxyFactoryBean extends AbstractSingletonProxyFactoryBean
implements FactoryBean, BeanFactoryAware {
@Override
protected Object createMainInterceptor() {
return new NoOpAdvice();
}
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
}
}

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>
<alias name="someMessageSource" alias="myMessageSource"/>
</beans>

View File

@@ -0,0 +1,10 @@
<?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>
<alias name="myMessageSource" alias="someMessageSource"/>
<bean id="myMessageSource" class="org.springframework.context.support.StaticMessageSource"/>
</beans>

View File

@@ -0,0 +1,14 @@
<?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 name="assemblerOne" class="org.springframework.context.support.TestProxyFactoryBean">
<property name="target"><ref parent="assemblerOne"/></property>
</bean>
<bean name="assemblerTwo" class="org.springframework.context.support.TestProxyFactoryBean">
<property name="target"><ref parent="assemblerTwo"/></property>
</bean>
</beans>

View File

@@ -0,0 +1,17 @@
<?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 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties">
<props>
<prop key="msClass">StaticMessageSource</prop>
<prop key="msScope">singleton</prop>
</props>
</property>
</bean>
<bean id="someMessageSource" class="org.springframework.context.support.${msClass}" scope="${msScope}"/>
</beans>

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="someMessageSource" class="org.springframework.context.support.StaticMessageSourc" lazy-init="true"/>
</beans>

View File

@@ -0,0 +1,11 @@
<?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="someMessageSource" class="org.springframework.context.support.StaticMessageSource">
<property name="useCodeAsDefaultMessage" value="xxx"/>
<property name="alwaysUseMessageFormat" value="yyy"/>
</bean>
</beans>

View File

@@ -0,0 +1,19 @@
<?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="bean4" class="org.springframework.context.support.LifecycleTestBean" depends-on="bean2"/>
<bean id="bean3" class="org.springframework.context.support.LifecycleTestBean" depends-on="bean2"/>
<bean id="bean1" class="org.springframework.context.support.LifecycleTestBean"/>
<bean id="bean2" class="org.springframework.context.support.LifecycleTestBean" depends-on="bean1"/>
<bean id="bean2Proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="bean2"/>
</bean>
</beans>

View File

@@ -0,0 +1,5 @@
code1 = mess\
age1
code2=message2
hello={0}, {1}
escaped=I''m

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties version="1.0">
<entry key="code2">nachricht2xml</entry>
</properties>

View File

@@ -0,0 +1,2 @@
wrappedAssemblerOne.proxyTargetClass=true
wrappedAssemblerTwo.proxyTargetClass=true

View File

@@ -0,0 +1,3 @@
targetName=wrappedAssemblerOne
logicName=logicTwo
realLogicName=realLogic

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="someMessageSource" name="yourMessageSource"
class="org.springframework.context.support.StaticMessageSource"/>
<bean class="org.springframework.context.support.ClassPathXmlApplicationContext" lazy-init="true">
<constructor-arg value="someNonExistentFile.xml"/>
</bean>
</beans>

View File

@@ -0,0 +1,19 @@
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:property-placeholder location="org/springframework/context/support/placeholder.properties"/>
<bean name="realLogic" class="org.springframework.context.support.Logic">
<!--<property name="assembler"><ref bean="assemblerOne"/></property>-->
<property name="assembler"><ref bean="myTarget"/></property>
</bean>
<alias name="${targetName}" alias="myTarget"/>
<alias name="${realLogicName}" alias="${logicName}"/>
</beans>

View File

@@ -0,0 +1,38 @@
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<import resource="import1.xml"/>
<import resource="classpath:org/springframework/context/support/test/*/import2.xml"/>
<context:property-override location="org/springframework/context/support/override.properties"/>
<bean id="messageSource" class="org.springframework.context.support.StaticMessageSource"/>
<bean class="org.springframework.context.support.FactoryBeanAndApplicationListener"/>
<bean name="service" class="org.springframework.context.support.Service" dependency-check="objects">
<property name="resources" value="/org/springframework/context/support/test/context*.xml"/>
</bean>
<bean name="service2" class="org.springframework.context.support.Service" autowire="byName" depends-on="service">
<property name="resources" value="/org/springframework/context/support/test/context*.xml"/>
</bean>
<bean name="autowiredService" class="org.springframework.context.support.AutowiredService" autowire="byName"/>
<bean name="autowiredService2" class="org.springframework.context.support.AutowiredService" autowire="byType"/>
<bean name="wrappedAssemblerOne" class="org.springframework.context.support.TestProxyFactoryBean">
<property name="target" ref="assemblerOne"/>
</bean>
<bean name="wrappedAssemblerTwo" class="org.springframework.context.support.TestProxyFactoryBean">
<property name="target" ref="assemblerTwo"/>
</bean>
</beans>

View File

@@ -0,0 +1,11 @@
<?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 name="logicOne" class="org.springframework.context.support.Logic">
<!--<property name="assembler"><ref bean="assemblerTwo"/></property>-->
<property name="assembler"><ref bean="wrappedAssemblerTwo"/></property>
</bean>
</beans>

View File

@@ -0,0 +1,17 @@
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:property-placeholder location="org/springframework/context/support/placeholder.properties"/>
<context:property-placeholder/>
<bean name="logicTwo" class="org.springframework.context.support.Logic">
<!--<property name="assembler"><ref bean="assemblerOne"/></property>-->
<property name="assembler"><ref bean="${targetName}"/></property>
</bean>
</beans>

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 name="assemblerOne" class="org.springframework.context.support.Assembler">
<property name="service"><ref bean="service"/></property>
<property name="logic"><ref bean="logicOne"/></property>
</bean>
<bean name="inheritingAssemblerOne" parent="assemblerTwo">
<property name="logic"><ref bean="logicOne"/></property>
</bean>
</beans>

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 name="assemblerTwo" parent="assemblerOne">
<property name="logic"><ref bean="logicTwo"/></property>
</bean>
<!-- Returns void (null) -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="java.lang.System.gc"/>
</bean>
</beans>

View File

@@ -0,0 +1,42 @@
# this must only be used for ApplicationContexts, some classes are only appropriate for application contexts
rod.(class)=org.springframework.beans.TestBean
rod.name=Rod
rod.age=31
roderick.(parent)=rod
roderick.name=Roderick
kerry.(class)=org.springframework.beans.TestBean
kerry.name=Kerry
kerry.age=34
kerry.spouse(ref)=rod
kathy.(class)=org.springframework.beans.TestBean
kathy.(singleton)=false
typeMismatch.(class)=org.springframework.beans.TestBean
typeMismatch.name=typeMismatch
typeMismatch.age=34x
typeMismatch.spouse(ref)=rod
typeMismatch.(singleton)=false
validEmpty.(class)=org.springframework.beans.TestBean
listenerVeto.(class)=org.springframework.beans.TestBean
typeMismatch.name=typeMismatch
typeMismatch.age=34x
typeMismatch.spouse(ref)=rod
singletonFactory.(class)=org.springframework.beans.factory.DummyFactory
singletonFactory.singleton=true
prototypeFactory.(class)=org.springframework.beans.factory.DummyFactory
prototypeFactory.singleton=false
mustBeInitialized.(class)=org.springframework.beans.factory.MustBeInitialized
lifecycle.(class)=org.springframework.context.LifecycleContextBean
lifecyclePostProcessor.(class)=org.springframework.beans.factory.LifecycleBean$PostProcessor