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;
}
}
}
OK、Expert 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 : この機能は、MultiActionController の代わりに SimpleFormController で満たすことができることを知っています。しかし、それは単なる例として示されているだけで、他には何もありません