使用Grails v3.3.9。
访问稳定的 Controller 时出错。 grails网站显示了这一点
URI
/api/device
Class
java.lang.NoSuchMethodException
Message
Error creating bean with name 'com.softwood.controller.DeviceController': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.softwood.controller.DeviceController]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.softwood.controller.DeviceController.<init>()
Caused by
com.softwood.controller.DeviceController.<init>()
我已经像这样设置了UrlMapping
get "/api/device"(controller:"device", action:"index")
我的 Controller 像这样扩展了RestfulController,这不允许将默认构造函数添加到类中
class DeviceController extends RestfulController<Device> {
static responseFormats = ['json', 'xml']
//static scaffold = Device
DeviceController(Class<Device> device) {
this(device, false)
}
DeviceController(Class<Device> device, boolean readOnly) {
super(device, readOnly)
}
def index (Integer max) {
params.max = Math.min(max ?: 10, 100)
Collection<Device> results = Device.list(sort:"name")
respond results, deviceCount: Device.count()
}
def show (Device device) {
if(device == null) {
render status:404
} else {respond device}
}
}
这里有一个链接,多数民众赞成在相关Extending RestfulController for a base SubClassRestfulController is not working on grails 3.0.4
但是,我已经清理了构建,重新运行等都没有用。我遇到相同的实例化失败
允许从RestfulController扩展的解决办法是什么?
最佳答案
那是不对的。您的构造函数不应接受Class
作为参数。您需要没有参数的构造函数。
class DeviceController extends RestfulController<Device> {
static responseFormats = ['json', 'xml']
DeviceController() {
super(Device)
/* If you want it to be read only, use super(Device, true)
instead of super(Device)
*/
}
// ...
}
当Spring创建 Controller 实例时,它不会将任何内容传递给构造函数,因此您需要no-arg构造函数。