Spring架构增强MultiActionController(3)

我们可以在MultiActionController中定义一个PropertiesMethodNameResolver类型的成员变量“propertiesMethodNameResoler”。和定义一个Properties类型的成员变量“urlMethodmappings”在MultiActionController的bean进行配置的时候把urlMethodmappings的值作为propertiesMethodNameResoler的mapping的值。然后再调用MultiActionController的setMethodNameResolver()方法,把propertiesMethodNameResoler设置为MultiActionController的methodNameResolver的属性值。要做到这一些还应该实现InitializingBean接口。






public class MultiMethodController extends MultiActionController implements
InitializingBean ...{

private Properties urlMethodmappings;
public void afterPropertiesSet() throws Exception ...{
if (urlMethodmappings != null && !urlMethodmappings.isEmpty()) ...{

PropertiesMethodNameResolver propertiesMethodNameResolver
= new PropertiesMethodNameResolver();
propertiesMethodNameResolver.setMappings(urlMethodmappings);
this.setMethodNameResolver(propertiesMethodNameResolver);
if (this.logger.isInfoEnabled()) ...{
this.logger.info("binding success...... ");
}
} else ...{
logger.info("no 'urlMethodmappings' set on MultiMethodController");
}
}
/**//**
* @return Returns the urlMethodmappings.
*/
public Properties getUrlMethodmappings() ...{
return urlMethodmappings;
}

/**//**
* @param urlMethodmappings
* The urlMethodmappings to set.
*/
public void setUrlMethodmappings(Properties urlMethodmappings) ...{
this.urlMethodmappings = urlMethodmappings;
}
}


在afterPropertiesSet中,






PropertiesMethodNameResolver propertiesMethodNameResolver
= new PropertiesMethodNameResolver();


创建一个默认的PropertiesMethodNameResolver的实例






propertiesMethodNameResolver.setMappings(urlMethodmappings);


把urlMethodmappings作为propertiesMethodNameResolver的mapping属性值






this.setMethodNameResolver(propertiesMethodNameResolver);


调用父类方法,把propertiesMethodNameResolver注入MethodNameResolver属性中。


注意,在这里我命名为MultiMethodController是为了与MultiActionController区别。

通过这样的代码,简化了原本复杂的配置。


4.2通过一个commandName属性,可以让用户自由决定绑定对象的名称


MultiActionController的getCommandName如下:






public static final String DEFAULT_COMMAND_NAME = "command";
protected String getCommandName(Object command) ...{
return DEFAULT_COMMAND_NAME;
}


MultiActionController并没有一个setCommandName的方法,所以我们需要一个setCommandName的方法,然后重写getCommandName(Object command)方法






private String commandName =DEFAULT_COMMAND_NAME;
public String getCommandName() ...{
return commandName;
}
public void setCommandName(String commandName) ...{
this.commandName = commandName;
}
protected String getCommandName(Object object) ...{
return this.getCommandName();
}


如果没有设置commandName属性,默认值为“command”,通过setCommandName方法就可以自由的去决定comamnd对象的名称了。

你可能感兴趣的:(controller)