SpringMVC中的自定义bean实例化逻辑
我有一个Spring MVC应用程序试图使用富域模型,在Controller类中有以下映射:SpringMVC中的自定义bean实例化逻辑,spring,spring-mvc,Spring,Spring Mvc,我有一个Spring MVC应用程序试图使用富域模型,在Controller类中有以下映射: @RequestMapping(value = "/entity", method = RequestMethod.POST) public String create(@Valid Entity entity, BindingResult result, ModelMap modelMap) { if (entity== null) throw new Illegal
@RequestMapping(value = "/entity", method = RequestMethod.POST)
public String create(@Valid Entity entity, BindingResult result, ModelMap modelMap) {
if (entity== null) throw new IllegalArgumentException("An entity is required");
if (result.hasErrors()) {
modelMap.addAttribute("entity", entity);
return "entity/create";
}
entity.persist();
return "redirect:/entity/" + entity.getId();
}
在执行此方法之前,Spring使用BeanUtils
实例化一个新的实体
并填充其字段。它使用的是:
...
ReflectionUtils.makeAccessible(ctor);
return ctor.newInstance(args);
问题是:
我的实体是Spring管理的bean。这样做的原因是在它们上注入DAO。我没有调用new
,而是使用EntityFactory.createEntity()
。当从数据库中检索它们时,我有一个拦截器覆盖
public Object instantiate(String entityName, EntityMode entityMode, Serializable id)
方法,并将工厂与之挂钩
因此,这里缺少的最后一个谜题是如何迫使Spring使用工厂而不是它自己的BeanUtils反射方法?有没有关于清洁解决方案的建议
非常感谢。您可以使用
@modeldattribute
-annotated方法用bean预填充模型。然后数据绑定器将使用该bean,而不是实例化新bean。然而,这将影响控制器的所有方法
@ModelAttribute
public Entity createEntity() { ... }
您可以使用
@modeldattribute
-annotated方法用bean预填充模型。然后数据绑定器将使用该bean,而不是实例化新bean。然而,这将影响控制器的所有方法
@ModelAttribute
public Entity createEntity() { ... }