Grails 基本控制器中的springSecurityService为null
这是一个相当奇怪的问题,我已经研究了一段时间,所以我快发疯了 我有一个控制器扩展另一个控制器,因此我可以有多个控制器继承一个方法,它们是这样的:Grails 基本控制器中的springSecurityService为null,grails,spring-security,Grails,Spring Security,这是一个相当奇怪的问题,我已经研究了一段时间,所以我快发疯了 我有一个控制器扩展另一个控制器,因此我可以有多个控制器继承一个方法,它们是这样的: class EventController extends EventAwareController { def springSecurityService def edit = { // this line prints out principal id println springSecurity
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”
空对象位于
com.ticketbranch.EventAwareController.getAuthorizedEventById(EventAwareController.groovy:14)
但是我在EventController中的prinln语句打印主体id时没有任何问题?!?那么springSecurityService在EventAwareController中被注入为null
有什么想法吗?建议?谢谢。这两个类中都有字段,这在使用Groovy时是个问题。Grails中的依赖项注入通常与您现在所做的一样,使用
def
。这是一个公共字段,因此Groovy为其创建了一个公共getter和setter,并将该字段设置为私有。getter没有被使用,但是Spring看到了setter,并且由于bean被配置为按名称(而不是按类型)连接,所以bean被注入,因为setter名称(setSpringSecurityService
)和bean名称之间存在匹配
因为有两次,所以有两个二传手和一个胜利者,所以在一个类中私有字段的值为空
但是像任何公共(或受保护)属性一样,依赖注入是继承的,所以只需将其从所有子类中删除并保留在基类中即可。非常酷的回答,我花了一个小时试图了解发生了什么……感谢您帮助我了解发生了什么:)