gpt4 book ai didi

spring-mvc - Spring MVC 中的通用 Controller

转载 作者:行者123 更新时间:2023-12-03 12:14:03 27 4
gpt4 key购买 nike

我一直在尝试编写一个通用 Controller 来提高代码的可重用性。以下是我到目前为止所拥有的:

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可以是国家、项目、注册和用户等内容。我现在面临的问题是 Autowiring 过程失败并出现以下错误:
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 的构造函数参数类(class):

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
}
}

然后你可以为每个扩展它的子类使用 Autowiring :
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 ,可以基于泛型类型 Autowiring 。因此,您可以使用通用 BaseService<Country>作为 Autowiring 构造函数时的参数,Spring 仍然能够确定哪个是正确的,而不会抛出任何 NoSuchBeanDefinitionException :
@Controller
public class CountryController extends CRUDController<Country> {

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

关于spring-mvc - Spring MVC 中的通用 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17016663/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com