2010-06-11 110 views
1

这里去这需要从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来填充。但它只是作为一个例子显示,没有别的

+0

你有使用'MultiActionController'的原因吗?它在Spring 3中被弃用了,你真的应该使用'@ Controller'来代替它,这很容易。 – skaffman 2010-06-11 20:32:42

+0

@skaffman对不起,我不使用Spring 3。0(我知道它在Spring 3.0中被弃用),我可以通过配置获得相同的约定,而无需Spring 3.0 MVC注释。谢谢! – 2010-06-11 20:36:59

+0

你也可以在Spring 2.5中使用'@ Controller',你不需要3.0。命令 - 对象绑定更容易理解。而且你的代码已经充斥着Spring MVC注解,我不明白你不愿意使用'@ Controller'。 – skaffman 2010-06-11 20:39:32

回答

1

我敢肯定,他的意思是使用lookup-method系统中chapter 3 of the spring reference manual

只有记录下来的一面是,<lookup-method>需要一个没有ARG方法,而不是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 bean这是不可能的(当然在< 3)做到这一点与注释。

+0

谢谢。我想你是对的。没有办法通过使用Spring注释来获得相同的行为? – 2010-06-12 20:38:00