gpt4 book ai didi

grails - 为什么使用与配置的 SpringBean 名称相同的操作名称会导致 ClassCastException?

转载 作者:行者123 更新时间:2023-12-02 14:35:50 24 4
gpt4 key购买 nike

要重现此问题,请使用以下步骤。

  • 创建一个新的 Grails 应用程序。
  • 创建一个名为 FooController
  • 的新 Controller
  • 将 Action “bar”添加到 FooController
  • 在 src/groovy 中,创建一个名为 Bar
  • 的新类
  • 在 resources.groovy 中配置一个名为 bar 的 SpringBean
    bar(Bar) {bean ->
    bean.autowire = 'byName'
    }
  • 启动应用程序并导航到 http:localhost:8080/[appContext]/foo/bar
  • 你应该得到一个类似这样的堆栈跟踪:
  • java.lang.ClassCastException: Bar cannot be cast to groovy.lang.Closure
    at org.grails.plugin.resource.DevModeSanityFilter.doFilter(DevModeSanityFilter.groovy:44)
    at java.lang.Thread.run(Thread.java:680)'

    为什么会出现这种情况?它是 Grails 中的错误还是预期的行为?

    我希望配置的 SpringBeans 和操作名称之间不应该有名称冲突。

    最佳答案

    问题是 Groovy 语法像

    class FooController {
    def bar = {
    // do something
    }
    }

    给出 FooController第二类公共(public)方法
    public Object getBar() {
    return bar;
    }

    public void setBar(Object newBar) {
    bar = newBar;
    }
    setBar的存在方法使 Spring 将其视为要 Autowiring 的属性,并用您的 bean 替换闭包值。 Grails 本身只需要 getter 方法,所以如果你说
    class FooController {
    final bar = {
    // do something
    }
    }

    (即声明 barfinal )然后 Groovy 将只合成 getter 而不是 setter,Spring 将看不到 bar作为一个属性,它可以 Autowiring 。

    关于grails - 为什么使用与配置的 SpringBean 名称相同的操作名称会导致 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12088174/

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