【问题标题】:springSecurityService is null in base controllerspringSecurityService 在基本控制器中为空
【发布时间】:2011-11-28 04:22:06
【问题描述】:

这是一个相当奇怪的问题,我已经解决了一段时间,所以我要疯了。

我有一个控制器扩展了另一个控制器,所以我可以让多个控制器继承一个方法,它们会像这样:

class EventController extends EventAwareController {

    def springSecurityService

    def edit = {
        // this line prints out principal id
        println springSecurityService.principal.id
        def eventInstance = getAuthorizedEventById(params.id)
        if (!eventInstance) {
            flash.message = "${message(code: 'event.not.found.message')}"
            redirect(action: "list", controller: "event")
            return false
        }
}

class EventAwareController {
    def eventService
    def springSecurityService

    def getAuthorizedEventById(def eventId) {
        def event
        if (eventId) {
            // this springSecurityService is null and throws an error
            event = eventService.findAuthorizedEvent(eventId, springSecurityService.principal.id)
            if (event) {
                session.eventId = eventId
            }
        }
        return event
    }

}

EventAwareController 正在抛出:

java.lang.NullPointerException: 无法获取属性'principal' on 空对象在 com.ticketbranch.EventAwareController.getAuthorizedEventById(EventAwareController.groovy:14)

但是我在 EventController 中的 prinln 语句打印主体 ID 没有任何问题?!?那么springSecurityService在EventAwareController中被注入为null?

有什么想法吗?建议?谢谢。

【问题讨论】:

    标签: grails spring-security


    【解决方案1】:

    您在两个类中都有该字段,这是使用 Groovy 时的一个问题。 Grails 中的依赖注入通常像您正在做的那样使用def <beanname> 完成。这是一个公共字段,因此 Groovy 为其创建了一个公共 getter 和 setter,并将该字段设为私有。没有使用 getter,但是 Spring 看到了 setter,并且由于 bean 被配置为按名称(而不是按类型)连接,因此 bean 被注入,因为 setter 名称(setSpringSecurityService)和 bean 名称之间存在匹配.

    因为你有两次,你有两个二传手和一个胜利,所以你将有一个类中的私有字段的空值。

    但与任何公共(或受保护)属性一样,依赖注入是继承的,因此只需将其从所有子类中删除并保留在基类中即可。

    【讨论】:

    • 非常酷的答案,我花了一个小时试图了解发生了什么...感谢您帮助我了解发生了什么:)
    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2015-01-31
    • 2019-06-02
    相关资源
    最近更新 更多