我建议您将
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"); }}


