这是一个需要从 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 的实例来初始化地址属性。否则,我将得到 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 专家说
Options for alternate object creation include pulling an instance from a BeanFactory or using method injection to transparently return a new instance.
第一个选项
- 从 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());
}
但是他想通过使用方法注入(inject)透明地返回一个新实例来表达什么???你能展示我如何实现他所说的吗???
ATT:我知道这个功能可以由 SimpleFormController 而不是 MultiActionController 来填充。但是它只是作为示例显示,没有其他内容
最佳答案
我很确定他的意思是使用 lookup-method
系统如 chapter 3 of the spring reference manual 中所述
唯一的缺点是<lookup-method>
需要无参数方法而不是 newCommandObject(Class)
MultiActionController
的方法.
这可以通过以下方式解决:
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 配置 Controller bean,这是不可能的(当然在 <3 中)使用注释来做到这一点。
关于java - 关于使用Spring框架创建实例的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3026008/