Spring MVC中的通用控制器


问题内容

我一直在尝试编写一个通用控制器来提高代码的可重用性。以下是我到目前为止的内容:

public abstract class CRUDController<T> {

    @Autowired
    private BaseService<T> service;

    @RequestMapping(value = "/validation.json", method = RequestMethod.POST)
    @ResponseBody
    public ValidationResponse ajaxValidation(@Valid T t,
            BindingResult result) {
        ValidationResponse res = new ValidationResponse();
        if (!result.hasErrors()) {
            res.setStatus("SUCCESS");
        } else {
            res.setStatus("FAIL");
            List<FieldError> allErrors = result.getFieldErrors();
            List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
            for (FieldError objectError : allErrors) {
                errorMesages.add(new ErrorMessage(objectError.getField(),
                        objectError.getDefaultMessage()));
            }
            res.setErrorMessageList(errorMesages);
        }
        return res;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initForm(Model model) {
        service.initializeForm(model);
        return "country"; // how can I make this generic too ?
    }
}

T可以是国家,项目,注册和用户之类的内容。我现在面临的问题是自动装配过程失败,并出现以下错误:

No unique bean of type [com.ucmas.cms.service.BaseService] is defined: expected single matching bean but found 4: [countryServiceImpl, itemServiceImpl, registrationServiceImpl, userServiceImpl].

是否有可能实现我的需求?我怎样才能解决这个问题 ?


问题答案:

我建议您将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实现:

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

更新:

Spring 4.0 RC1开始,可以根据泛型类型自动装配。因此,您可以BaseService<Country>在自动装配构造器时将泛型用作参数,而Spring仍然可以找出正确的参数而不会抛出任何错误NoSuchBeanDefinitionException

@Controller
public class CountryController extends CRUDController<Country> {

    @Autowired
    public CountryController(BaseService<Country> countryService) {
        super(countryService, "country");
    }
}