簡體   English   中英

有關使用Spring框架創建實例的問題?

[英]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提取實例或使用方法注入透明地返回新實例。

第一選擇

  • 從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方法,而不是MultiActionControllernewCommandObject(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM