gpt4 book ai didi

java - 将 Groovy 动态方法添加到 Spring Controller

转载 作者:行者123 更新时间:2023-11-29 08:49:23 32 4
gpt4 key购买 nike

有一个 Groovy Spring 应用程序,我正在尝试在应用程序启动时向 Controller 类添加一个方法。喜欢:

@Configuration
class AppConfig implements InitializingBean {
void afterPropertiesSet() throws Exception {
MyCtrl ctrl = applicationContext.getBean(...)
ctrl.metaClass.render = { String x ->
...
}
}
}

对于像这样的 Groovy 类:

@Controller
class MyCtrl {

ModelAndView show() {
...
println this.metaClass.methods*.name
println MyCtrl.metaClass.methods*.name
println this
println this.class == MyCtrl
render('show')
}

}

并得到异常:

groovy.lang.MissingMethodException: No signature of method: com.company.MyCtrl.render() is applicable for argument types: (java.lang.String) values: [/index]
Possible solutions: render(java.lang.String), index(), find(), every(), every(groovy.lang.Closure), find(groovy.lang.Closure)

请注意,Groovy 在“可能的解决方案”列表中提到了此方法。

在控制台中我看到以下内容:

[equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait, __$swapInit, getMetaClass, getProperty, index, invokeMethod, setMetaClass, setProperty]

[render, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait, __$swapInit, getMetaClass, getProperty, index, invokeMethod, setMetaClass, setProperty]

com.company.MyCtrl@3e52f8c1

true

如我所见,this.metaClass 没有看到我的动态方法 render,但是 MyCtrl.metaClass 看到了它。当然,它是同一个类,MyCtrl == this.getClass()

有什么区别?我错过了什么?尝试使用 ExpandoMetaClass 和/或应用类而不是实例,结果相同。不起作用。

这不是我第一次通过元类添加方法,而且一直运行良好。只是第一次添加到 Spring Controller 。也许它与用于 Controller 的 Spring 反射冲突?不确定如何检查

PS Groovy 2.3、Java 7、Spring 4.0.3

最佳答案

你有这个...

MyCtrl ctrl = applicationContext.getBean(...)
ctrl.metaClass.render = { String x ->
...
}

那不是修改 MyCtrl 元类。那就是修改 MyCtrl 的特定实例的元类。根据您的应用中您的描述中不存在的其他一些因素,这可能不是您想要的。你可能想用这样的东西修改 MyCtrl 元类......

MyCtrl.metaClass.render = { String x ->
...
}

关于java - 将 Groovy 动态方法添加到 Spring Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23514787/

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