栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring MVC中的通用控制器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring MVC中的通用控制器

我建议您将

baseService
作为构造函数参数添加到
CRUDController
类中:

public abstract class CRUDController<T> {    private final baseService<T> service;    private final String initFormParam;    public CRUDController(baseService<T> service, String initFormParam) {        this.service = service;        this.initFormParam;    }    @RequestMapping(value = "/validation.json", method = RequestMethod.POST)    @ResponseBody    public ValidationResponse ajaxValidation(@Valid T t, BindingResult result) {        // same as in the example        return res;    }    @RequestMapping(method = RequestMethod.GET)    public String initForm(Model model) {        service.initializeForm(model);        return initFormParam;   // Now initialized by the constructor    }}

然后,您可以对扩展它的每个子类使用自动装配:

public class CountryController extends CRUDController<Country> {    @Autowired    public CountryController(CountryService countryService) {        super(countryService, "country");    }}

另外,您可以在构造函数中使用@Qualifier批注来区分不同的

baseService
实现:

@Autowiredpublic CountryController(@Qualifier("countryServiceImpl") baseService<Country> baseService) {    super(baseService, "country");}

更新:

从Spring 4.0 RC1开始,可以根据泛型类型自动装配。因此,您可以

baseService<Country>
在自动装配构造器时将泛型用作参数,而Spring仍然可以找出正确的参数而不会抛出任何错误
NoSuchBeanDefinitionException

@Controllerpublic class CountryController extends CRUDController<Country> {    @Autowired    public CountryController(baseService<Country> countryService) {        super(countryService, "country");    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/443331.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号