这里去这需要从Spring表单填充命令对象关于使用Spring框架创建实例的问题?
public class Person {
private String name;
private Integer age;
/**
* on-demand initialized
*/
private Address address;
// getter's and setter's
}
和地址
public class Address {
private String street;
// getter's and setter's
}
现在假设下面的MultiActionController
@Component
public class PersonController extends MultiActionController {
@Autowired
@Qualifier("personRepository")
private Repository<Person, Integer> personRepository;
/**
* mapped To /person/add
*/
public ModelAndView add(HttpServletRequest request, HttpServletResponse response, Person person) throws Exception {
personRepository.add(person);
return new ModelAndView("redirect:/home.htm");
}
}
因为人需要地址属性按需初始化,我需要覆盖newCommandObject创建Person的实例来启动地址属性。否则,我会得到NullPointerException异常
@Component
public class PersonController extends MultiActionController {
/**
* code as shown above
*/
@Override
public Object newCommandObject(Class clazz) thorws Exception {
if(clazz.isAssignableFrom(Person.class)) {
Person person = new Person();
person.setAddress(new Address());
return person;
}
}
}
好,专家Spring MVC和Web Flow的说,对备选对象创建
选项包括将BeanFactory拉一个实例或使用方法注入透明地返回新实例。
首先选择
- 将BeanFactory拉一个实例
可以写成
@Override
public Object newCommandObject(Class clazz) thorws Exception {
/**
* Will retrieve a prototype instance from ApplicationContext whose name matchs its clazz.getSimpleName()
*/
getApplicationContext().getBean(clazz.getSimpleName());
}
但到底是什么,他想用方法注入到由说透明返回一个新的inst ance ???你能展示我如何实现他所说的吗?
ATT:我知道这个funcionality可以由SimpleFormController而不是MultiActionController来填充。但它只是作为一个例子显示,没有别的
你有使用'MultiActionController'的原因吗?它在Spring 3中被弃用了,你真的应该使用'@ Controller'来代替它,这很容易。 – skaffman 2010-06-11 20:32:42
@skaffman对不起,我不使用Spring 3。0(我知道它在Spring 3.0中被弃用),我可以通过配置获得相同的约定,而无需Spring 3.0 MVC注释。谢谢! – 2010-06-11 20:36:59
你也可以在Spring 2.5中使用'@ Controller',你不需要3.0。命令 - 对象绑定更容易理解。而且你的代码已经充斥着Spring MVC注解,我不明白你不愿意使用'@ Controller'。 – skaffman 2010-06-11 20:39:32