DWR在和spring集成時(shí),在dwr.xml中將設(shè)置creator="spring",告訴dwr將使用dwr的org.directwebremoting.spring.SpringCreator來(lái)創(chuàng)建對(duì)象實(shí)例,但是SpringCreator.getType地處理是不適當(dāng)?shù)?讓我們來(lái)看看它的源碼[dwr-3.0.0.116]:
public Class<?> getType()
{
if (clazz == null)
{
try
{
clazz = getInstance().getClass();
}
catch (InstantiationException ex)
{
log.error("Failed to instansiate object to detect type.", ex);
return Object.class;
}
}
return clazz;
}
我們?cè)賮?lái)看看它的getInstance,最終由spring來(lái)創(chuàng)建實(shí)例.
public Object getInstance() throws InstantiationException
{
try
{
if (overrideFactory != null)
{
return overrideFactory.getBean(beanName);
}
if (factory == null)
{
factory = getBeanFactory();
}
if (factory == null)
{
log.error("DWR can't find a spring config. See following info logs for solutions");
log.info("- Option 1. In dwr.xml, <create creator='spring' ...> add
log.info("- Option 2. Use a spring org.springframework.web.context.ContextLoaderListener.");
log.info("- Option 3. Call SpringCreator.setOverrideBeanFactory() from your web-app");
throw new InstantiationException("DWR can't find a spring config. See the logs for solutions");
}
return factory.getBean(beanName);
}
catch (InstantiationException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new InstantiationException("Illegal Access to default constructor on " + clazz.getName() + " due to: " + ex);
}
}
getInstance將返回由spring來(lái)創(chuàng)建的實(shí)例,很明顯SpringCreator.getType有點(diǎn)多此一舉,它先創(chuàng)建了實(shí)例,再?gòu)膶?shí)例的getClass獲取對(duì)象的類(lèi)型,而spring的beanFactory.getType同樣有此功能,但它不需要先創(chuàng)建實(shí)例.
也許寫(xiě)這位代碼的仁兄是不知道spring beanFactory.getType這個(gè)方法吧!
我把SpringCreator.getType改正后的代碼 如下:
public Class<?> getType()
{
if (clazz == null)
{
try
{
if(overrideFactory != null){
clazz=overrideFactory.getType(beanName);
}else {
if(factory == null)
factory = getBeanFactory();
clazz=factory.getType(beanName);
}
}
catch (Exception ex)
{
log.error("Failed to detect type.", ex);
return Object.class;
}
}
return clazz;
}
如果出現(xiàn)
Error loading class for creator ...... 那么就修改SpringCreator吧!