[英]Question about instance creation by using Spring framework?
这是一个需要从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;
}
}
}
好的,Expert Spring MVC和Web Flow说
创建备用对象的选项包括从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来填补。 但这只是一个例子而已
我很确定他的意思是使用spring参考手册第3章中记录的lookup-method
系统
唯一的newCommandObject(Class)
是<lookup-method>
需要一个no arg方法,而不是MultiActionController
的newCommandObject(Class)
方法。
这可以通过以下方式解决:
public abstract class PersonController extends MultiActionController {
/**
* code as shown above
*/
@Override
public Object newCommandObject(Class clazz) thorws Exception {
if(clazz.isAssignableFrom(Person.class)) {
return newPerson();
}
}
public abstract Person newPerson();
}
在上下文文件中:
<bean id="personController" class="org.yourapp.PersonController">
<lookup-method name="newPerson" bean="personPrototype"/>
</bean>
不利的一面是,使用这种方法会使您有点无法通过xml配置控制器bean(肯定在<3中),并且不能使用批注进行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.