在spring的工程裏,bean的定義是不可避免的。雖然有各種可以減少很多bean的配置,特別是action衆多的時候,我們通常可以通過引入autowire攔截器來避免action類bean的定義。但還會有衆多的bean需要定義,他們之間的依賴關係通常也是複雜、多變的。在這過程中我們通常會發生一些弱智的錯誤,而這些錯誤也通常需要等到spring容器啓動後,甚至在頁面調到相應功能時才能被發現(其實你如果有寫單元測試的習慣是不會發生這種情況的)。下面是我的一個簡單的junit單元測試,我用來對bean的依賴檢查,在每加入新bean或是改動到bean代碼後
跑一下,希望對初學者有所幫助。
ublic class SpringFactoryTest extends AbstractDependencyInjectionSpringContextTests ...{
@Override
protected String[] getConfigLocations() ...{
return new String[] ...{ "classpath:applicationContext-*.xml" };
}
public void testAllBeanDefined() throws Exception ...{
System.out.println("There are " + applicationContext.getBeanDefinitionCount() + " beans was defined.");
String[] beanNames = applicationContext.getBeanDefinitionNames();
Integer errorCount = 0;
for (String beanName : beanNames) ...{
try ...{
Object bean = applicationContext.getBean(beanName);
assertNotNull(bean);
} catch (BeanIsAbstractException e) ...{
} catch (Exception e) ...{
errorCount++;
System.out.println(e.getMessage());
}
}
if (errorCount > 0)...{
System.out.println("There are "+errorCount +" beans error");
fail();
}
}
}
@Override
protected String[] getConfigLocations() ...{
return new String[] ...{ "classpath:applicationContext-*.xml" };
}
public void testAllBeanDefined() throws Exception ...{
System.out.println("There are " + applicationContext.getBeanDefinitionCount() + " beans was defined.");
String[] beanNames = applicationContext.getBeanDefinitionNames();
Integer errorCount = 0;
for (String beanName : beanNames) ...{
try ...{
Object bean = applicationContext.getBean(beanName);
assertNotNull(bean);
} catch (BeanIsAbstractException e) ...{
} catch (Exception e) ...{
errorCount++;
System.out.println(e.getMessage());
}
}
if (errorCount > 0)...{
System.out.println("There are "+errorCount +" beans error");
fail();
}
}
}