这是一个需要从 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");
}
}
因为 Person 的 Address 属性需要按需初始化,所以我需要重写newCommandObject来创建 Person 的实例来初始化 address 属性。否则,我会得到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());
}
但是他用方法注入透明地返回一个新实例到底想说什么???你能告诉我如何实施他所说的吗???
ATT:我知道这个功能可以由 SimpleFormController 而不是 MultiActionController 来填充。但它仅作为示例显示,仅此而已