【问题标题】:How to initialize injected form-backing model bean?如何初始化注入的表单支持模型bean?
【发布时间】:2017-09-13 09:02:22
【问题描述】:

所以我有模型实体Place,它必须初始化一些关系。 现在我在控制器中使用自动创建的模型表单支持 bean,如下所示:

@GetMapping(value = "/add")
public String addPlacePage(final Place place, Model model) {
    model.addAttribute("services", serviceRepository.findAll())
            .addAttribute("categories", categoryRepository.findAll())
            .addAttribute("cities", cityRepository.findAll());
    return "admin/place/addPlace";
}

Place place 是我的 Spring 创建的(可能是 Spring-MVC)。有没有办法为支持bean提供工厂方法?我不想在控制器中这样做。

我曾尝试将工厂代码放入我的配置中,如下所示:

@Bean
@Scope(value = "prototype")
public Place place() {
    log.info("Creating place in FACTORY");
    Place place = EntityFactory.emptyPlace();
    return place;
}

但这不起作用。

【问题讨论】:

    标签: javascript spring spring-mvc spring-boot


    【解决方案1】:

    所以我在 freenode 的#spring 频道中提出了同样的问题,这要感谢用户 。为了做我想做的事,@ModelAttribute 方法应该像这样在控制器中定义:

    @ModelAttribute
    private Place emptyPlace(){
        log.info("Creating place in FACTORY");
        Place place = EntityFactory.emptyPlace();
        return place;
    }
    

    和相关文档在这里 https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-modelattrib-methods

    【讨论】:

      猜你喜欢
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 2010-11-03
      • 2016-07-22
      相关资源
      最近更新 更多